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

1.334   ! brouard     1: /* $Id: imach.c,v 1.333 2022/08/21 09:10:30 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.334   ! brouard     4:   Revision 1.333  2022/08/21 09:10:30  brouard
        !             5:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
        !             6:   reassigning covariates: my first idea was that people will always
        !             7:   use the first covariate V1 into the model but in fact they are
        !             8:   producing data with many covariates and can use an equation model
        !             9:   with some of the covariate; it means that in a model V2+V3 instead
        !            10:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
        !            11:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
        !            12:   the equation model is restricted to two variables only (V2, V3)
        !            13:   and the combination for V2 should be codtabm(k,1) instead of
        !            14:   (codtabm(k,2), and the code should be
        !            15:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
        !            16:   made. All of these should be simplified once a day like we did in
        !            17:   hpxij() for example by using precov[nres] which is computed in
        !            18:   decoderesult for each nres of each resultline. Loop should be done
        !            19:   on the equation model globally by distinguishing only product with
        !            20:   age (which are changing with age) and no more on type of
        !            21:   covariates, single dummies, single covariates.
        !            22: 
1.333     brouard    23:   Revision 1.332  2022/08/21 09:06:25  brouard
                     24:   Summary: Version 0.99r33
                     25: 
                     26:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     27:   reassigning covariates: my first idea was that people will always
                     28:   use the first covariate V1 into the model but in fact they are
                     29:   producing data with many covariates and can use an equation model
                     30:   with some of the covariate; it means that in a model V2+V3 instead
                     31:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     32:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     33:   the equation model is restricted to two variables only (V2, V3)
                     34:   and the combination for V2 should be codtabm(k,1) instead of
                     35:   (codtabm(k,2), and the code should be
                     36:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     37:   made. All of these should be simplified once a day like we did in
                     38:   hpxij() for example by using precov[nres] which is computed in
                     39:   decoderesult for each nres of each resultline. Loop should be done
                     40:   on the equation model globally by distinguishing only product with
                     41:   age (which are changing with age) and no more on type of
                     42:   covariates, single dummies, single covariates.
                     43: 
1.332     brouard    44:   Revision 1.331  2022/08/07 05:40:09  brouard
                     45:   *** empty log message ***
                     46: 
1.331     brouard    47:   Revision 1.330  2022/08/06 07:18:25  brouard
                     48:   Summary: last 0.99r31
                     49: 
                     50:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     51: 
1.330     brouard    52:   Revision 1.329  2022/08/03 17:29:54  brouard
                     53:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     54: 
1.329     brouard    55:   Revision 1.328  2022/07/27 17:40:48  brouard
                     56:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     57: 
1.328     brouard    58:   Revision 1.327  2022/07/27 14:47:35  brouard
                     59:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     60: 
1.327     brouard    61:   Revision 1.326  2022/07/26 17:33:55  brouard
                     62:   Summary: some test with nres=1
                     63: 
1.326     brouard    64:   Revision 1.325  2022/07/25 14:27:23  brouard
                     65:   Summary: r30
                     66: 
                     67:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     68:   coredumped, revealed by Feiuno, thank you.
                     69: 
1.325     brouard    70:   Revision 1.324  2022/07/23 17:44:26  brouard
                     71:   *** empty log message ***
                     72: 
1.324     brouard    73:   Revision 1.323  2022/07/22 12:30:08  brouard
                     74:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     75: 
1.323     brouard    76:   Revision 1.322  2022/07/22 12:27:48  brouard
                     77:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     78: 
1.322     brouard    79:   Revision 1.321  2022/07/22 12:04:24  brouard
                     80:   Summary: r28
                     81: 
                     82:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     83: 
1.321     brouard    84:   Revision 1.320  2022/06/02 05:10:11  brouard
                     85:   *** empty log message ***
                     86: 
1.320     brouard    87:   Revision 1.319  2022/06/02 04:45:11  brouard
                     88:   * imach.c (Module): Adding the Wald tests from the log to the main
                     89:   htm for better display of the maximum likelihood estimators.
                     90: 
1.319     brouard    91:   Revision 1.318  2022/05/24 08:10:59  brouard
                     92:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     93:   of confidencce intervals with product in the equation modelC
                     94: 
1.318     brouard    95:   Revision 1.317  2022/05/15 15:06:23  brouard
                     96:   * imach.c (Module):  Some minor improvements
                     97: 
1.317     brouard    98:   Revision 1.316  2022/05/11 15:11:31  brouard
                     99:   Summary: r27
                    100: 
1.316     brouard   101:   Revision 1.315  2022/05/11 15:06:32  brouard
                    102:   *** empty log message ***
                    103: 
1.315     brouard   104:   Revision 1.314  2022/04/13 17:43:09  brouard
                    105:   * imach.c (Module): Adding link to text data files
                    106: 
1.314     brouard   107:   Revision 1.313  2022/04/11 15:57:42  brouard
                    108:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    109: 
1.313     brouard   110:   Revision 1.312  2022/04/05 21:24:39  brouard
                    111:   *** empty log message ***
                    112: 
1.312     brouard   113:   Revision 1.311  2022/04/05 21:03:51  brouard
                    114:   Summary: Fixed quantitative covariates
                    115: 
                    116:          Fixed covariates (dummy or quantitative)
                    117:        with missing values have never been allowed but are ERRORS and
                    118:        program quits. Standard deviations of fixed covariates were
                    119:        wrongly computed. Mean and standard deviations of time varying
                    120:        covariates are still not computed.
                    121: 
1.311     brouard   122:   Revision 1.310  2022/03/17 08:45:53  brouard
                    123:   Summary: 99r25
                    124: 
                    125:   Improving detection of errors: result lines should be compatible with
                    126:   the model.
                    127: 
1.310     brouard   128:   Revision 1.309  2021/05/20 12:39:14  brouard
                    129:   Summary: Version 0.99r24
                    130: 
1.309     brouard   131:   Revision 1.308  2021/03/31 13:11:57  brouard
                    132:   Summary: Version 0.99r23
                    133: 
                    134: 
                    135:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    136: 
1.308     brouard   137:   Revision 1.307  2021/03/08 18:11:32  brouard
                    138:   Summary: 0.99r22 fixed bug on result:
                    139: 
1.307     brouard   140:   Revision 1.306  2021/02/20 15:44:02  brouard
                    141:   Summary: Version 0.99r21
                    142: 
                    143:   * imach.c (Module): Fix bug on quitting after result lines!
                    144:   (Module): Version 0.99r21
                    145: 
1.306     brouard   146:   Revision 1.305  2021/02/20 15:28:30  brouard
                    147:   * imach.c (Module): Fix bug on quitting after result lines!
                    148: 
1.305     brouard   149:   Revision 1.304  2021/02/12 11:34:20  brouard
                    150:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    151: 
1.304     brouard   152:   Revision 1.303  2021/02/11 19:50:15  brouard
                    153:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    154: 
1.303     brouard   155:   Revision 1.302  2020/02/22 21:00:05  brouard
                    156:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    157:   and life table from the data without any state)
                    158: 
1.302     brouard   159:   Revision 1.301  2019/06/04 13:51:20  brouard
                    160:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    161: 
1.301     brouard   162:   Revision 1.300  2019/05/22 19:09:45  brouard
                    163:   Summary: version 0.99r19 of May 2019
                    164: 
1.300     brouard   165:   Revision 1.299  2019/05/22 18:37:08  brouard
                    166:   Summary: Cleaned 0.99r19
                    167: 
1.299     brouard   168:   Revision 1.298  2019/05/22 18:19:56  brouard
                    169:   *** empty log message ***
                    170: 
1.298     brouard   171:   Revision 1.297  2019/05/22 17:56:10  brouard
                    172:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    173: 
1.297     brouard   174:   Revision 1.296  2019/05/20 13:03:18  brouard
                    175:   Summary: Projection syntax simplified
                    176: 
                    177: 
                    178:   We can now start projections, forward or backward, from the mean date
                    179:   of inteviews up to or down to a number of years of projection:
                    180:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    181:   or
                    182:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    183:   or
                    184:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    185:   or
                    186:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    187: 
1.296     brouard   188:   Revision 1.295  2019/05/18 09:52:50  brouard
                    189:   Summary: doxygen tex bug
                    190: 
1.295     brouard   191:   Revision 1.294  2019/05/16 14:54:33  brouard
                    192:   Summary: There was some wrong lines added
                    193: 
1.294     brouard   194:   Revision 1.293  2019/05/09 15:17:34  brouard
                    195:   *** empty log message ***
                    196: 
1.293     brouard   197:   Revision 1.292  2019/05/09 14:17:20  brouard
                    198:   Summary: Some updates
                    199: 
1.292     brouard   200:   Revision 1.291  2019/05/09 13:44:18  brouard
                    201:   Summary: Before ncovmax
                    202: 
1.291     brouard   203:   Revision 1.290  2019/05/09 13:39:37  brouard
                    204:   Summary: 0.99r18 unlimited number of individuals
                    205: 
                    206:   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.
                    207: 
1.290     brouard   208:   Revision 1.289  2018/12/13 09:16:26  brouard
                    209:   Summary: Bug for young ages (<-30) will be in r17
                    210: 
1.289     brouard   211:   Revision 1.288  2018/05/02 20:58:27  brouard
                    212:   Summary: Some bugs fixed
                    213: 
1.288     brouard   214:   Revision 1.287  2018/05/01 17:57:25  brouard
                    215:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    216: 
1.287     brouard   217:   Revision 1.286  2018/04/27 14:27:04  brouard
                    218:   Summary: some minor bugs
                    219: 
1.286     brouard   220:   Revision 1.285  2018/04/21 21:02:16  brouard
                    221:   Summary: Some bugs fixed, valgrind tested
                    222: 
1.285     brouard   223:   Revision 1.284  2018/04/20 05:22:13  brouard
                    224:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    225: 
1.284     brouard   226:   Revision 1.283  2018/04/19 14:49:16  brouard
                    227:   Summary: Some minor bugs fixed
                    228: 
1.283     brouard   229:   Revision 1.282  2018/02/27 22:50:02  brouard
                    230:   *** empty log message ***
                    231: 
1.282     brouard   232:   Revision 1.281  2018/02/27 19:25:23  brouard
                    233:   Summary: Adding second argument for quitting
                    234: 
1.281     brouard   235:   Revision 1.280  2018/02/21 07:58:13  brouard
                    236:   Summary: 0.99r15
                    237: 
                    238:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    239: 
1.280     brouard   240:   Revision 1.279  2017/07/20 13:35:01  brouard
                    241:   Summary: temporary working
                    242: 
1.279     brouard   243:   Revision 1.278  2017/07/19 14:09:02  brouard
                    244:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    245: 
1.278     brouard   246:   Revision 1.277  2017/07/17 08:53:49  brouard
                    247:   Summary: BOM files can be read now
                    248: 
1.277     brouard   249:   Revision 1.276  2017/06/30 15:48:31  brouard
                    250:   Summary: Graphs improvements
                    251: 
1.276     brouard   252:   Revision 1.275  2017/06/30 13:39:33  brouard
                    253:   Summary: Saito's color
                    254: 
1.275     brouard   255:   Revision 1.274  2017/06/29 09:47:08  brouard
                    256:   Summary: Version 0.99r14
                    257: 
1.274     brouard   258:   Revision 1.273  2017/06/27 11:06:02  brouard
                    259:   Summary: More documentation on projections
                    260: 
1.273     brouard   261:   Revision 1.272  2017/06/27 10:22:40  brouard
                    262:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    263: 
1.272     brouard   264:   Revision 1.271  2017/06/27 10:17:50  brouard
                    265:   Summary: Some bug with rint
                    266: 
1.271     brouard   267:   Revision 1.270  2017/05/24 05:45:29  brouard
                    268:   *** empty log message ***
                    269: 
1.270     brouard   270:   Revision 1.269  2017/05/23 08:39:25  brouard
                    271:   Summary: Code into subroutine, cleanings
                    272: 
1.269     brouard   273:   Revision 1.268  2017/05/18 20:09:32  brouard
                    274:   Summary: backprojection and confidence intervals of backprevalence
                    275: 
1.268     brouard   276:   Revision 1.267  2017/05/13 10:25:05  brouard
                    277:   Summary: temporary save for backprojection
                    278: 
1.267     brouard   279:   Revision 1.266  2017/05/13 07:26:12  brouard
                    280:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    281: 
1.266     brouard   282:   Revision 1.265  2017/04/26 16:22:11  brouard
                    283:   Summary: imach 0.99r13 Some bugs fixed
                    284: 
1.265     brouard   285:   Revision 1.264  2017/04/26 06:01:29  brouard
                    286:   Summary: Labels in graphs
                    287: 
1.264     brouard   288:   Revision 1.263  2017/04/24 15:23:15  brouard
                    289:   Summary: to save
                    290: 
1.263     brouard   291:   Revision 1.262  2017/04/18 16:48:12  brouard
                    292:   *** empty log message ***
                    293: 
1.262     brouard   294:   Revision 1.261  2017/04/05 10:14:09  brouard
                    295:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    296: 
1.261     brouard   297:   Revision 1.260  2017/04/04 17:46:59  brouard
                    298:   Summary: Gnuplot indexations fixed (humm)
                    299: 
1.260     brouard   300:   Revision 1.259  2017/04/04 13:01:16  brouard
                    301:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    302: 
1.259     brouard   303:   Revision 1.258  2017/04/03 10:17:47  brouard
                    304:   Summary: Version 0.99r12
                    305: 
                    306:   Some cleanings, conformed with updated documentation.
                    307: 
1.258     brouard   308:   Revision 1.257  2017/03/29 16:53:30  brouard
                    309:   Summary: Temp
                    310: 
1.257     brouard   311:   Revision 1.256  2017/03/27 05:50:23  brouard
                    312:   Summary: Temporary
                    313: 
1.256     brouard   314:   Revision 1.255  2017/03/08 16:02:28  brouard
                    315:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    316: 
1.255     brouard   317:   Revision 1.254  2017/03/08 07:13:00  brouard
                    318:   Summary: Fixing data parameter line
                    319: 
1.254     brouard   320:   Revision 1.253  2016/12/15 11:59:41  brouard
                    321:   Summary: 0.99 in progress
                    322: 
1.253     brouard   323:   Revision 1.252  2016/09/15 21:15:37  brouard
                    324:   *** empty log message ***
                    325: 
1.252     brouard   326:   Revision 1.251  2016/09/15 15:01:13  brouard
                    327:   Summary: not working
                    328: 
1.251     brouard   329:   Revision 1.250  2016/09/08 16:07:27  brouard
                    330:   Summary: continue
                    331: 
1.250     brouard   332:   Revision 1.249  2016/09/07 17:14:18  brouard
                    333:   Summary: Starting values from frequencies
                    334: 
1.249     brouard   335:   Revision 1.248  2016/09/07 14:10:18  brouard
                    336:   *** empty log message ***
                    337: 
1.248     brouard   338:   Revision 1.247  2016/09/02 11:11:21  brouard
                    339:   *** empty log message ***
                    340: 
1.247     brouard   341:   Revision 1.246  2016/09/02 08:49:22  brouard
                    342:   *** empty log message ***
                    343: 
1.246     brouard   344:   Revision 1.245  2016/09/02 07:25:01  brouard
                    345:   *** empty log message ***
                    346: 
1.245     brouard   347:   Revision 1.244  2016/09/02 07:17:34  brouard
                    348:   *** empty log message ***
                    349: 
1.244     brouard   350:   Revision 1.243  2016/09/02 06:45:35  brouard
                    351:   *** empty log message ***
                    352: 
1.243     brouard   353:   Revision 1.242  2016/08/30 15:01:20  brouard
                    354:   Summary: Fixing a lots
                    355: 
1.242     brouard   356:   Revision 1.241  2016/08/29 17:17:25  brouard
                    357:   Summary: gnuplot problem in Back projection to fix
                    358: 
1.241     brouard   359:   Revision 1.240  2016/08/29 07:53:18  brouard
                    360:   Summary: Better
                    361: 
1.240     brouard   362:   Revision 1.239  2016/08/26 15:51:03  brouard
                    363:   Summary: Improvement in Powell output in order to copy and paste
                    364: 
                    365:   Author:
                    366: 
1.239     brouard   367:   Revision 1.238  2016/08/26 14:23:35  brouard
                    368:   Summary: Starting tests of 0.99
                    369: 
1.238     brouard   370:   Revision 1.237  2016/08/26 09:20:19  brouard
                    371:   Summary: to valgrind
                    372: 
1.237     brouard   373:   Revision 1.236  2016/08/25 10:50:18  brouard
                    374:   *** empty log message ***
                    375: 
1.236     brouard   376:   Revision 1.235  2016/08/25 06:59:23  brouard
                    377:   *** empty log message ***
                    378: 
1.235     brouard   379:   Revision 1.234  2016/08/23 16:51:20  brouard
                    380:   *** empty log message ***
                    381: 
1.234     brouard   382:   Revision 1.233  2016/08/23 07:40:50  brouard
                    383:   Summary: not working
                    384: 
1.233     brouard   385:   Revision 1.232  2016/08/22 14:20:21  brouard
                    386:   Summary: not working
                    387: 
1.232     brouard   388:   Revision 1.231  2016/08/22 07:17:15  brouard
                    389:   Summary: not working
                    390: 
1.231     brouard   391:   Revision 1.230  2016/08/22 06:55:53  brouard
                    392:   Summary: Not working
                    393: 
1.230     brouard   394:   Revision 1.229  2016/07/23 09:45:53  brouard
                    395:   Summary: Completing for func too
                    396: 
1.229     brouard   397:   Revision 1.228  2016/07/22 17:45:30  brouard
                    398:   Summary: Fixing some arrays, still debugging
                    399: 
1.227     brouard   400:   Revision 1.226  2016/07/12 18:42:34  brouard
                    401:   Summary: temp
                    402: 
1.226     brouard   403:   Revision 1.225  2016/07/12 08:40:03  brouard
                    404:   Summary: saving but not running
                    405: 
1.225     brouard   406:   Revision 1.224  2016/07/01 13:16:01  brouard
                    407:   Summary: Fixes
                    408: 
1.224     brouard   409:   Revision 1.223  2016/02/19 09:23:35  brouard
                    410:   Summary: temporary
                    411: 
1.223     brouard   412:   Revision 1.222  2016/02/17 08:14:50  brouard
                    413:   Summary: Probably last 0.98 stable version 0.98r6
                    414: 
1.222     brouard   415:   Revision 1.221  2016/02/15 23:35:36  brouard
                    416:   Summary: minor bug
                    417: 
1.220     brouard   418:   Revision 1.219  2016/02/15 00:48:12  brouard
                    419:   *** empty log message ***
                    420: 
1.219     brouard   421:   Revision 1.218  2016/02/12 11:29:23  brouard
                    422:   Summary: 0.99 Back projections
                    423: 
1.218     brouard   424:   Revision 1.217  2015/12/23 17:18:31  brouard
                    425:   Summary: Experimental backcast
                    426: 
1.217     brouard   427:   Revision 1.216  2015/12/18 17:32:11  brouard
                    428:   Summary: 0.98r4 Warning and status=-2
                    429: 
                    430:   Version 0.98r4 is now:
                    431:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    432:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    433:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    434: 
1.216     brouard   435:   Revision 1.215  2015/12/16 08:52:24  brouard
                    436:   Summary: 0.98r4 working
                    437: 
1.215     brouard   438:   Revision 1.214  2015/12/16 06:57:54  brouard
                    439:   Summary: temporary not working
                    440: 
1.214     brouard   441:   Revision 1.213  2015/12/11 18:22:17  brouard
                    442:   Summary: 0.98r4
                    443: 
1.213     brouard   444:   Revision 1.212  2015/11/21 12:47:24  brouard
                    445:   Summary: minor typo
                    446: 
1.212     brouard   447:   Revision 1.211  2015/11/21 12:41:11  brouard
                    448:   Summary: 0.98r3 with some graph of projected cross-sectional
                    449: 
                    450:   Author: Nicolas Brouard
                    451: 
1.211     brouard   452:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   453:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   454:   Summary: Adding ftolpl parameter
                    455:   Author: N Brouard
                    456: 
                    457:   We had difficulties to get smoothed confidence intervals. It was due
                    458:   to the period prevalence which wasn't computed accurately. The inner
                    459:   parameter ftolpl is now an outer parameter of the .imach parameter
                    460:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    461:   computation are long.
                    462: 
1.209     brouard   463:   Revision 1.208  2015/11/17 14:31:57  brouard
                    464:   Summary: temporary
                    465: 
1.208     brouard   466:   Revision 1.207  2015/10/27 17:36:57  brouard
                    467:   *** empty log message ***
                    468: 
1.207     brouard   469:   Revision 1.206  2015/10/24 07:14:11  brouard
                    470:   *** empty log message ***
                    471: 
1.206     brouard   472:   Revision 1.205  2015/10/23 15:50:53  brouard
                    473:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    474: 
1.205     brouard   475:   Revision 1.204  2015/10/01 16:20:26  brouard
                    476:   Summary: Some new graphs of contribution to likelihood
                    477: 
1.204     brouard   478:   Revision 1.203  2015/09/30 17:45:14  brouard
                    479:   Summary: looking at better estimation of the hessian
                    480: 
                    481:   Also a better criteria for convergence to the period prevalence And
                    482:   therefore adding the number of years needed to converge. (The
                    483:   prevalence in any alive state shold sum to one
                    484: 
1.203     brouard   485:   Revision 1.202  2015/09/22 19:45:16  brouard
                    486:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    487: 
1.202     brouard   488:   Revision 1.201  2015/09/15 17:34:58  brouard
                    489:   Summary: 0.98r0
                    490: 
                    491:   - Some new graphs like suvival functions
                    492:   - Some bugs fixed like model=1+age+V2.
                    493: 
1.201     brouard   494:   Revision 1.200  2015/09/09 16:53:55  brouard
                    495:   Summary: Big bug thanks to Flavia
                    496: 
                    497:   Even model=1+age+V2. did not work anymore
                    498: 
1.200     brouard   499:   Revision 1.199  2015/09/07 14:09:23  brouard
                    500:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    501: 
1.199     brouard   502:   Revision 1.198  2015/09/03 07:14:39  brouard
                    503:   Summary: 0.98q5 Flavia
                    504: 
1.198     brouard   505:   Revision 1.197  2015/09/01 18:24:39  brouard
                    506:   *** empty log message ***
                    507: 
1.197     brouard   508:   Revision 1.196  2015/08/18 23:17:52  brouard
                    509:   Summary: 0.98q5
                    510: 
1.196     brouard   511:   Revision 1.195  2015/08/18 16:28:39  brouard
                    512:   Summary: Adding a hack for testing purpose
                    513: 
                    514:   After reading the title, ftol and model lines, if the comment line has
                    515:   a q, starting with #q, the answer at the end of the run is quit. It
                    516:   permits to run test files in batch with ctest. The former workaround was
                    517:   $ echo q | imach foo.imach
                    518: 
1.195     brouard   519:   Revision 1.194  2015/08/18 13:32:00  brouard
                    520:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    521: 
1.194     brouard   522:   Revision 1.193  2015/08/04 07:17:42  brouard
                    523:   Summary: 0.98q4
                    524: 
1.193     brouard   525:   Revision 1.192  2015/07/16 16:49:02  brouard
                    526:   Summary: Fixing some outputs
                    527: 
1.192     brouard   528:   Revision 1.191  2015/07/14 10:00:33  brouard
                    529:   Summary: Some fixes
                    530: 
1.191     brouard   531:   Revision 1.190  2015/05/05 08:51:13  brouard
                    532:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    533: 
                    534:   Fix 1+age+.
                    535: 
1.190     brouard   536:   Revision 1.189  2015/04/30 14:45:16  brouard
                    537:   Summary: 0.98q2
                    538: 
1.189     brouard   539:   Revision 1.188  2015/04/30 08:27:53  brouard
                    540:   *** empty log message ***
                    541: 
1.188     brouard   542:   Revision 1.187  2015/04/29 09:11:15  brouard
                    543:   *** empty log message ***
                    544: 
1.187     brouard   545:   Revision 1.186  2015/04/23 12:01:52  brouard
                    546:   Summary: V1*age is working now, version 0.98q1
                    547: 
                    548:   Some codes had been disabled in order to simplify and Vn*age was
                    549:   working in the optimization phase, ie, giving correct MLE parameters,
                    550:   but, as usual, outputs were not correct and program core dumped.
                    551: 
1.186     brouard   552:   Revision 1.185  2015/03/11 13:26:42  brouard
                    553:   Summary: Inclusion of compile and links command line for Intel Compiler
                    554: 
1.185     brouard   555:   Revision 1.184  2015/03/11 11:52:39  brouard
                    556:   Summary: Back from Windows 8. Intel Compiler
                    557: 
1.184     brouard   558:   Revision 1.183  2015/03/10 20:34:32  brouard
                    559:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    560: 
                    561:   We use directest instead of original Powell test; probably no
                    562:   incidence on the results, but better justifications;
                    563:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    564:   wrong results.
                    565: 
1.183     brouard   566:   Revision 1.182  2015/02/12 08:19:57  brouard
                    567:   Summary: Trying to keep directest which seems simpler and more general
                    568:   Author: Nicolas Brouard
                    569: 
1.182     brouard   570:   Revision 1.181  2015/02/11 23:22:24  brouard
                    571:   Summary: Comments on Powell added
                    572: 
                    573:   Author:
                    574: 
1.181     brouard   575:   Revision 1.180  2015/02/11 17:33:45  brouard
                    576:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    577: 
1.180     brouard   578:   Revision 1.179  2015/01/04 09:57:06  brouard
                    579:   Summary: back to OS/X
                    580: 
1.179     brouard   581:   Revision 1.178  2015/01/04 09:35:48  brouard
                    582:   *** empty log message ***
                    583: 
1.178     brouard   584:   Revision 1.177  2015/01/03 18:40:56  brouard
                    585:   Summary: Still testing ilc32 on OSX
                    586: 
1.177     brouard   587:   Revision 1.176  2015/01/03 16:45:04  brouard
                    588:   *** empty log message ***
                    589: 
1.176     brouard   590:   Revision 1.175  2015/01/03 16:33:42  brouard
                    591:   *** empty log message ***
                    592: 
1.175     brouard   593:   Revision 1.174  2015/01/03 16:15:49  brouard
                    594:   Summary: Still in cross-compilation
                    595: 
1.174     brouard   596:   Revision 1.173  2015/01/03 12:06:26  brouard
                    597:   Summary: trying to detect cross-compilation
                    598: 
1.173     brouard   599:   Revision 1.172  2014/12/27 12:07:47  brouard
                    600:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    601: 
1.172     brouard   602:   Revision 1.171  2014/12/23 13:26:59  brouard
                    603:   Summary: Back from Visual C
                    604: 
                    605:   Still problem with utsname.h on Windows
                    606: 
1.171     brouard   607:   Revision 1.170  2014/12/23 11:17:12  brouard
                    608:   Summary: Cleaning some \%% back to %%
                    609: 
                    610:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    611: 
1.170     brouard   612:   Revision 1.169  2014/12/22 23:08:31  brouard
                    613:   Summary: 0.98p
                    614: 
                    615:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    616: 
1.169     brouard   617:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   618:   Summary: update
1.169     brouard   619: 
1.168     brouard   620:   Revision 1.167  2014/12/22 13:50:56  brouard
                    621:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    622: 
                    623:   Testing on Linux 64
                    624: 
1.167     brouard   625:   Revision 1.166  2014/12/22 11:40:47  brouard
                    626:   *** empty log message ***
                    627: 
1.166     brouard   628:   Revision 1.165  2014/12/16 11:20:36  brouard
                    629:   Summary: After compiling on Visual C
                    630: 
                    631:   * imach.c (Module): Merging 1.61 to 1.162
                    632: 
1.165     brouard   633:   Revision 1.164  2014/12/16 10:52:11  brouard
                    634:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    635: 
                    636:   * imach.c (Module): Merging 1.61 to 1.162
                    637: 
1.164     brouard   638:   Revision 1.163  2014/12/16 10:30:11  brouard
                    639:   * imach.c (Module): Merging 1.61 to 1.162
                    640: 
1.163     brouard   641:   Revision 1.162  2014/09/25 11:43:39  brouard
                    642:   Summary: temporary backup 0.99!
                    643: 
1.162     brouard   644:   Revision 1.1  2014/09/16 11:06:58  brouard
                    645:   Summary: With some code (wrong) for nlopt
                    646: 
                    647:   Author:
                    648: 
                    649:   Revision 1.161  2014/09/15 20:41:41  brouard
                    650:   Summary: Problem with macro SQR on Intel compiler
                    651: 
1.161     brouard   652:   Revision 1.160  2014/09/02 09:24:05  brouard
                    653:   *** empty log message ***
                    654: 
1.160     brouard   655:   Revision 1.159  2014/09/01 10:34:10  brouard
                    656:   Summary: WIN32
                    657:   Author: Brouard
                    658: 
1.159     brouard   659:   Revision 1.158  2014/08/27 17:11:51  brouard
                    660:   *** empty log message ***
                    661: 
1.158     brouard   662:   Revision 1.157  2014/08/27 16:26:55  brouard
                    663:   Summary: Preparing windows Visual studio version
                    664:   Author: Brouard
                    665: 
                    666:   In order to compile on Visual studio, time.h is now correct and time_t
                    667:   and tm struct should be used. difftime should be used but sometimes I
                    668:   just make the differences in raw time format (time(&now).
                    669:   Trying to suppress #ifdef LINUX
                    670:   Add xdg-open for __linux in order to open default browser.
                    671: 
1.157     brouard   672:   Revision 1.156  2014/08/25 20:10:10  brouard
                    673:   *** empty log message ***
                    674: 
1.156     brouard   675:   Revision 1.155  2014/08/25 18:32:34  brouard
                    676:   Summary: New compile, minor changes
                    677:   Author: Brouard
                    678: 
1.155     brouard   679:   Revision 1.154  2014/06/20 17:32:08  brouard
                    680:   Summary: Outputs now all graphs of convergence to period prevalence
                    681: 
1.154     brouard   682:   Revision 1.153  2014/06/20 16:45:46  brouard
                    683:   Summary: If 3 live state, convergence to period prevalence on same graph
                    684:   Author: Brouard
                    685: 
1.153     brouard   686:   Revision 1.152  2014/06/18 17:54:09  brouard
                    687:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    688: 
1.152     brouard   689:   Revision 1.151  2014/06/18 16:43:30  brouard
                    690:   *** empty log message ***
                    691: 
1.151     brouard   692:   Revision 1.150  2014/06/18 16:42:35  brouard
                    693:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    694:   Author: brouard
                    695: 
1.150     brouard   696:   Revision 1.149  2014/06/18 15:51:14  brouard
                    697:   Summary: Some fixes in parameter files errors
                    698:   Author: Nicolas Brouard
                    699: 
1.149     brouard   700:   Revision 1.148  2014/06/17 17:38:48  brouard
                    701:   Summary: Nothing new
                    702:   Author: Brouard
                    703: 
                    704:   Just a new packaging for OS/X version 0.98nS
                    705: 
1.148     brouard   706:   Revision 1.147  2014/06/16 10:33:11  brouard
                    707:   *** empty log message ***
                    708: 
1.147     brouard   709:   Revision 1.146  2014/06/16 10:20:28  brouard
                    710:   Summary: Merge
                    711:   Author: Brouard
                    712: 
                    713:   Merge, before building revised version.
                    714: 
1.146     brouard   715:   Revision 1.145  2014/06/10 21:23:15  brouard
                    716:   Summary: Debugging with valgrind
                    717:   Author: Nicolas Brouard
                    718: 
                    719:   Lot of changes in order to output the results with some covariates
                    720:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    721:   improve the code.
                    722:   No more memory valgrind error but a lot has to be done in order to
                    723:   continue the work of splitting the code into subroutines.
                    724:   Also, decodemodel has been improved. Tricode is still not
                    725:   optimal. nbcode should be improved. Documentation has been added in
                    726:   the source code.
                    727: 
1.144     brouard   728:   Revision 1.143  2014/01/26 09:45:38  brouard
                    729:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    730: 
                    731:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    732:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    733: 
1.143     brouard   734:   Revision 1.142  2014/01/26 03:57:36  brouard
                    735:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    736: 
                    737:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    738: 
1.142     brouard   739:   Revision 1.141  2014/01/26 02:42:01  brouard
                    740:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    741: 
1.141     brouard   742:   Revision 1.140  2011/09/02 10:37:54  brouard
                    743:   Summary: times.h is ok with mingw32 now.
                    744: 
1.140     brouard   745:   Revision 1.139  2010/06/14 07:50:17  brouard
                    746:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    747:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    748: 
1.139     brouard   749:   Revision 1.138  2010/04/30 18:19:40  brouard
                    750:   *** empty log message ***
                    751: 
1.138     brouard   752:   Revision 1.137  2010/04/29 18:11:38  brouard
                    753:   (Module): Checking covariates for more complex models
                    754:   than V1+V2. A lot of change to be done. Unstable.
                    755: 
1.137     brouard   756:   Revision 1.136  2010/04/26 20:30:53  brouard
                    757:   (Module): merging some libgsl code. Fixing computation
                    758:   of likelione (using inter/intrapolation if mle = 0) in order to
                    759:   get same likelihood as if mle=1.
                    760:   Some cleaning of code and comments added.
                    761: 
1.136     brouard   762:   Revision 1.135  2009/10/29 15:33:14  brouard
                    763:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    764: 
1.135     brouard   765:   Revision 1.134  2009/10/29 13:18:53  brouard
                    766:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    767: 
1.134     brouard   768:   Revision 1.133  2009/07/06 10:21:25  brouard
                    769:   just nforces
                    770: 
1.133     brouard   771:   Revision 1.132  2009/07/06 08:22:05  brouard
                    772:   Many tings
                    773: 
1.132     brouard   774:   Revision 1.131  2009/06/20 16:22:47  brouard
                    775:   Some dimensions resccaled
                    776: 
1.131     brouard   777:   Revision 1.130  2009/05/26 06:44:34  brouard
                    778:   (Module): Max Covariate is now set to 20 instead of 8. A
                    779:   lot of cleaning with variables initialized to 0. Trying to make
                    780:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    781: 
1.130     brouard   782:   Revision 1.129  2007/08/31 13:49:27  lievre
                    783:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    784: 
1.129     lievre    785:   Revision 1.128  2006/06/30 13:02:05  brouard
                    786:   (Module): Clarifications on computing e.j
                    787: 
1.128     brouard   788:   Revision 1.127  2006/04/28 18:11:50  brouard
                    789:   (Module): Yes the sum of survivors was wrong since
                    790:   imach-114 because nhstepm was no more computed in the age
                    791:   loop. Now we define nhstepma in the age loop.
                    792:   (Module): In order to speed up (in case of numerous covariates) we
                    793:   compute health expectancies (without variances) in a first step
                    794:   and then all the health expectancies with variances or standard
                    795:   deviation (needs data from the Hessian matrices) which slows the
                    796:   computation.
                    797:   In the future we should be able to stop the program is only health
                    798:   expectancies and graph are needed without standard deviations.
                    799: 
1.127     brouard   800:   Revision 1.126  2006/04/28 17:23:28  brouard
                    801:   (Module): Yes the sum of survivors was wrong since
                    802:   imach-114 because nhstepm was no more computed in the age
                    803:   loop. Now we define nhstepma in the age loop.
                    804:   Version 0.98h
                    805: 
1.126     brouard   806:   Revision 1.125  2006/04/04 15:20:31  lievre
                    807:   Errors in calculation of health expectancies. Age was not initialized.
                    808:   Forecasting file added.
                    809: 
                    810:   Revision 1.124  2006/03/22 17:13:53  lievre
                    811:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    812:   The log-likelihood is printed in the log file
                    813: 
                    814:   Revision 1.123  2006/03/20 10:52:43  brouard
                    815:   * imach.c (Module): <title> changed, corresponds to .htm file
                    816:   name. <head> headers where missing.
                    817: 
                    818:   * imach.c (Module): Weights can have a decimal point as for
                    819:   English (a comma might work with a correct LC_NUMERIC environment,
                    820:   otherwise the weight is truncated).
                    821:   Modification of warning when the covariates values are not 0 or
                    822:   1.
                    823:   Version 0.98g
                    824: 
                    825:   Revision 1.122  2006/03/20 09:45:41  brouard
                    826:   (Module): Weights can have a decimal point as for
                    827:   English (a comma might work with a correct LC_NUMERIC environment,
                    828:   otherwise the weight is truncated).
                    829:   Modification of warning when the covariates values are not 0 or
                    830:   1.
                    831:   Version 0.98g
                    832: 
                    833:   Revision 1.121  2006/03/16 17:45:01  lievre
                    834:   * imach.c (Module): Comments concerning covariates added
                    835: 
                    836:   * imach.c (Module): refinements in the computation of lli if
                    837:   status=-2 in order to have more reliable computation if stepm is
                    838:   not 1 month. Version 0.98f
                    839: 
                    840:   Revision 1.120  2006/03/16 15:10:38  lievre
                    841:   (Module): refinements in the computation of lli if
                    842:   status=-2 in order to have more reliable computation if stepm is
                    843:   not 1 month. Version 0.98f
                    844: 
                    845:   Revision 1.119  2006/03/15 17:42:26  brouard
                    846:   (Module): Bug if status = -2, the loglikelihood was
                    847:   computed as likelihood omitting the logarithm. Version O.98e
                    848: 
                    849:   Revision 1.118  2006/03/14 18:20:07  brouard
                    850:   (Module): varevsij Comments added explaining the second
                    851:   table of variances if popbased=1 .
                    852:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    853:   (Module): Function pstamp added
                    854:   (Module): Version 0.98d
                    855: 
                    856:   Revision 1.117  2006/03/14 17:16:22  brouard
                    857:   (Module): varevsij Comments added explaining the second
                    858:   table of variances if popbased=1 .
                    859:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    860:   (Module): Function pstamp added
                    861:   (Module): Version 0.98d
                    862: 
                    863:   Revision 1.116  2006/03/06 10:29:27  brouard
                    864:   (Module): Variance-covariance wrong links and
                    865:   varian-covariance of ej. is needed (Saito).
                    866: 
                    867:   Revision 1.115  2006/02/27 12:17:45  brouard
                    868:   (Module): One freematrix added in mlikeli! 0.98c
                    869: 
                    870:   Revision 1.114  2006/02/26 12:57:58  brouard
                    871:   (Module): Some improvements in processing parameter
                    872:   filename with strsep.
                    873: 
                    874:   Revision 1.113  2006/02/24 14:20:24  brouard
                    875:   (Module): Memory leaks checks with valgrind and:
                    876:   datafile was not closed, some imatrix were not freed and on matrix
                    877:   allocation too.
                    878: 
                    879:   Revision 1.112  2006/01/30 09:55:26  brouard
                    880:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    881: 
                    882:   Revision 1.111  2006/01/25 20:38:18  brouard
                    883:   (Module): Lots of cleaning and bugs added (Gompertz)
                    884:   (Module): Comments can be added in data file. Missing date values
                    885:   can be a simple dot '.'.
                    886: 
                    887:   Revision 1.110  2006/01/25 00:51:50  brouard
                    888:   (Module): Lots of cleaning and bugs added (Gompertz)
                    889: 
                    890:   Revision 1.109  2006/01/24 19:37:15  brouard
                    891:   (Module): Comments (lines starting with a #) are allowed in data.
                    892: 
                    893:   Revision 1.108  2006/01/19 18:05:42  lievre
                    894:   Gnuplot problem appeared...
                    895:   To be fixed
                    896: 
                    897:   Revision 1.107  2006/01/19 16:20:37  brouard
                    898:   Test existence of gnuplot in imach path
                    899: 
                    900:   Revision 1.106  2006/01/19 13:24:36  brouard
                    901:   Some cleaning and links added in html output
                    902: 
                    903:   Revision 1.105  2006/01/05 20:23:19  lievre
                    904:   *** empty log message ***
                    905: 
                    906:   Revision 1.104  2005/09/30 16:11:43  lievre
                    907:   (Module): sump fixed, loop imx fixed, and simplifications.
                    908:   (Module): If the status is missing at the last wave but we know
                    909:   that the person is alive, then we can code his/her status as -2
                    910:   (instead of missing=-1 in earlier versions) and his/her
                    911:   contributions to the likelihood is 1 - Prob of dying from last
                    912:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    913:   the healthy state at last known wave). Version is 0.98
                    914: 
                    915:   Revision 1.103  2005/09/30 15:54:49  lievre
                    916:   (Module): sump fixed, loop imx fixed, and simplifications.
                    917: 
                    918:   Revision 1.102  2004/09/15 17:31:30  brouard
                    919:   Add the possibility to read data file including tab characters.
                    920: 
                    921:   Revision 1.101  2004/09/15 10:38:38  brouard
                    922:   Fix on curr_time
                    923: 
                    924:   Revision 1.100  2004/07/12 18:29:06  brouard
                    925:   Add version for Mac OS X. Just define UNIX in Makefile
                    926: 
                    927:   Revision 1.99  2004/06/05 08:57:40  brouard
                    928:   *** empty log message ***
                    929: 
                    930:   Revision 1.98  2004/05/16 15:05:56  brouard
                    931:   New version 0.97 . First attempt to estimate force of mortality
                    932:   directly from the data i.e. without the need of knowing the health
                    933:   state at each age, but using a Gompertz model: log u =a + b*age .
                    934:   This is the basic analysis of mortality and should be done before any
                    935:   other analysis, in order to test if the mortality estimated from the
                    936:   cross-longitudinal survey is different from the mortality estimated
                    937:   from other sources like vital statistic data.
                    938: 
                    939:   The same imach parameter file can be used but the option for mle should be -3.
                    940: 
1.324     brouard   941:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   942:   former routines in order to include the new code within the former code.
                    943: 
                    944:   The output is very simple: only an estimate of the intercept and of
                    945:   the slope with 95% confident intervals.
                    946: 
                    947:   Current limitations:
                    948:   A) Even if you enter covariates, i.e. with the
                    949:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    950:   B) There is no computation of Life Expectancy nor Life Table.
                    951: 
                    952:   Revision 1.97  2004/02/20 13:25:42  lievre
                    953:   Version 0.96d. Population forecasting command line is (temporarily)
                    954:   suppressed.
                    955: 
                    956:   Revision 1.96  2003/07/15 15:38:55  brouard
                    957:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    958:   rewritten within the same printf. Workaround: many printfs.
                    959: 
                    960:   Revision 1.95  2003/07/08 07:54:34  brouard
                    961:   * imach.c (Repository):
                    962:   (Repository): Using imachwizard code to output a more meaningful covariance
                    963:   matrix (cov(a12,c31) instead of numbers.
                    964: 
                    965:   Revision 1.94  2003/06/27 13:00:02  brouard
                    966:   Just cleaning
                    967: 
                    968:   Revision 1.93  2003/06/25 16:33:55  brouard
                    969:   (Module): On windows (cygwin) function asctime_r doesn't
                    970:   exist so I changed back to asctime which exists.
                    971:   (Module): Version 0.96b
                    972: 
                    973:   Revision 1.92  2003/06/25 16:30:45  brouard
                    974:   (Module): On windows (cygwin) function asctime_r doesn't
                    975:   exist so I changed back to asctime which exists.
                    976: 
                    977:   Revision 1.91  2003/06/25 15:30:29  brouard
                    978:   * imach.c (Repository): Duplicated warning errors corrected.
                    979:   (Repository): Elapsed time after each iteration is now output. It
                    980:   helps to forecast when convergence will be reached. Elapsed time
                    981:   is stamped in powell.  We created a new html file for the graphs
                    982:   concerning matrix of covariance. It has extension -cov.htm.
                    983: 
                    984:   Revision 1.90  2003/06/24 12:34:15  brouard
                    985:   (Module): Some bugs corrected for windows. Also, when
                    986:   mle=-1 a template is output in file "or"mypar.txt with the design
                    987:   of the covariance matrix to be input.
                    988: 
                    989:   Revision 1.89  2003/06/24 12:30:52  brouard
                    990:   (Module): Some bugs corrected for windows. Also, when
                    991:   mle=-1 a template is output in file "or"mypar.txt with the design
                    992:   of the covariance matrix to be input.
                    993: 
                    994:   Revision 1.88  2003/06/23 17:54:56  brouard
                    995:   * 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.
                    996: 
                    997:   Revision 1.87  2003/06/18 12:26:01  brouard
                    998:   Version 0.96
                    999: 
                   1000:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1001:   (Module): Change position of html and gnuplot routines and added
                   1002:   routine fileappend.
                   1003: 
                   1004:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1005:   * imach.c (Repository): Check when date of death was earlier that
                   1006:   current date of interview. It may happen when the death was just
                   1007:   prior to the death. In this case, dh was negative and likelihood
                   1008:   was wrong (infinity). We still send an "Error" but patch by
                   1009:   assuming that the date of death was just one stepm after the
                   1010:   interview.
                   1011:   (Repository): Because some people have very long ID (first column)
                   1012:   we changed int to long in num[] and we added a new lvector for
                   1013:   memory allocation. But we also truncated to 8 characters (left
                   1014:   truncation)
                   1015:   (Repository): No more line truncation errors.
                   1016: 
                   1017:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1018:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1019:   place. It differs from routine "prevalence" which may be called
                   1020:   many times. Probs is memory consuming and must be used with
                   1021:   parcimony.
                   1022:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1023: 
                   1024:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1025:   *** empty log message ***
                   1026: 
                   1027:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1028:   Add log in  imach.c and  fullversion number is now printed.
                   1029: 
                   1030: */
                   1031: /*
                   1032:    Interpolated Markov Chain
                   1033: 
                   1034:   Short summary of the programme:
                   1035:   
1.227     brouard  1036:   This program computes Healthy Life Expectancies or State-specific
                   1037:   (if states aren't health statuses) Expectancies from
                   1038:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1039: 
                   1040:   -1- a first survey ("cross") where individuals from different ages
                   1041:   are interviewed on their health status or degree of disability (in
                   1042:   the case of a health survey which is our main interest)
                   1043: 
                   1044:   -2- at least a second wave of interviews ("longitudinal") which
                   1045:   measure each change (if any) in individual health status.  Health
                   1046:   expectancies are computed from the time spent in each health state
                   1047:   according to a model. More health states you consider, more time is
                   1048:   necessary to reach the Maximum Likelihood of the parameters involved
                   1049:   in the model.  The simplest model is the multinomial logistic model
                   1050:   where pij is the probability to be observed in state j at the second
                   1051:   wave conditional to be observed in state i at the first
                   1052:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1053:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1054:   have a more complex model than "constant and age", you should modify
                   1055:   the program where the markup *Covariates have to be included here
                   1056:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1057:   convergence.
                   1058: 
                   1059:   The advantage of this computer programme, compared to a simple
                   1060:   multinomial logistic model, is clear when the delay between waves is not
                   1061:   identical for each individual. Also, if a individual missed an
                   1062:   intermediate interview, the information is lost, but taken into
                   1063:   account using an interpolation or extrapolation.  
                   1064: 
                   1065:   hPijx is the probability to be observed in state i at age x+h
                   1066:   conditional to the observed state i at age x. The delay 'h' can be
                   1067:   split into an exact number (nh*stepm) of unobserved intermediate
                   1068:   states. This elementary transition (by month, quarter,
                   1069:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1070:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1071:   and the contribution of each individual to the likelihood is simply
                   1072:   hPijx.
                   1073: 
                   1074:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1075:   of the life expectancies. It also computes the period (stable) prevalence.
                   1076: 
                   1077: Back prevalence and projections:
1.227     brouard  1078: 
                   1079:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1080:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1081:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1082:    mobilavproj)
                   1083: 
                   1084:     Computes the back prevalence limit for any combination of
                   1085:     covariate values k at any age between ageminpar and agemaxpar and
                   1086:     returns it in **bprlim. In the loops,
                   1087: 
                   1088:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1089:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1090: 
                   1091:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1092:    Computes for any combination of covariates k and any age between bage and fage 
                   1093:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1094:                        oldm=oldms;savm=savms;
1.227     brouard  1095: 
1.267     brouard  1096:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1097:      Computes the transition matrix starting at age 'age' over
                   1098:      'nhstepm*hstepm*stepm' months (i.e. until
                   1099:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1100:      nhstepm*hstepm matrices. 
                   1101: 
                   1102:      Returns p3mat[i][j][h] after calling
                   1103:      p3mat[i][j][h]=matprod2(newm,
                   1104:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1105:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1106:      oldm);
1.226     brouard  1107: 
                   1108: Important routines
                   1109: 
                   1110: - func (or funcone), computes logit (pij) distinguishing
                   1111:   o fixed variables (single or product dummies or quantitative);
                   1112:   o varying variables by:
                   1113:    (1) wave (single, product dummies, quantitative), 
                   1114:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1115:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1116:        % varying dummy (not done) or quantitative (not done);
                   1117: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1118:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1119: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1120:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1121:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1122: 
1.226     brouard  1123: 
                   1124:   
1.324     brouard  1125:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1126:            Institut national d'études démographiques, Paris.
1.126     brouard  1127:   This software have been partly granted by Euro-REVES, a concerted action
                   1128:   from the European Union.
                   1129:   It is copyrighted identically to a GNU software product, ie programme and
                   1130:   software can be distributed freely for non commercial use. Latest version
                   1131:   can be accessed at http://euroreves.ined.fr/imach .
                   1132: 
                   1133:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1134:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1135:   
                   1136:   **********************************************************************/
                   1137: /*
                   1138:   main
                   1139:   read parameterfile
                   1140:   read datafile
                   1141:   concatwav
                   1142:   freqsummary
                   1143:   if (mle >= 1)
                   1144:     mlikeli
                   1145:   print results files
                   1146:   if mle==1 
                   1147:      computes hessian
                   1148:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1149:       begin-prev-date,...
                   1150:   open gnuplot file
                   1151:   open html file
1.145     brouard  1152:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1153:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1154:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1155:     freexexit2 possible for memory heap.
                   1156: 
                   1157:   h Pij x                         | pij_nom  ficrestpij
                   1158:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1159:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1160:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1161: 
                   1162:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1163:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1164:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1165:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1166:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1167: 
1.126     brouard  1168:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1169:   health expectancies
                   1170:   Variance-covariance of DFLE
                   1171:   prevalence()
                   1172:    movingaverage()
                   1173:   varevsij() 
                   1174:   if popbased==1 varevsij(,popbased)
                   1175:   total life expectancies
                   1176:   Variance of period (stable) prevalence
                   1177:  end
                   1178: */
                   1179: 
1.187     brouard  1180: /* #define DEBUG */
                   1181: /* #define DEBUGBRENT */
1.203     brouard  1182: /* #define DEBUGLINMIN */
                   1183: /* #define DEBUGHESS */
                   1184: #define DEBUGHESSIJ
1.224     brouard  1185: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1186: #define POWELL /* Instead of NLOPT */
1.224     brouard  1187: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1188: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1189: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1190: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1191: 
                   1192: #include <math.h>
                   1193: #include <stdio.h>
                   1194: #include <stdlib.h>
                   1195: #include <string.h>
1.226     brouard  1196: #include <ctype.h>
1.159     brouard  1197: 
                   1198: #ifdef _WIN32
                   1199: #include <io.h>
1.172     brouard  1200: #include <windows.h>
                   1201: #include <tchar.h>
1.159     brouard  1202: #else
1.126     brouard  1203: #include <unistd.h>
1.159     brouard  1204: #endif
1.126     brouard  1205: 
                   1206: #include <limits.h>
                   1207: #include <sys/types.h>
1.171     brouard  1208: 
                   1209: #if defined(__GNUC__)
                   1210: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1211: #endif
                   1212: 
1.126     brouard  1213: #include <sys/stat.h>
                   1214: #include <errno.h>
1.159     brouard  1215: /* extern int errno; */
1.126     brouard  1216: 
1.157     brouard  1217: /* #ifdef LINUX */
                   1218: /* #include <time.h> */
                   1219: /* #include "timeval.h" */
                   1220: /* #else */
                   1221: /* #include <sys/time.h> */
                   1222: /* #endif */
                   1223: 
1.126     brouard  1224: #include <time.h>
                   1225: 
1.136     brouard  1226: #ifdef GSL
                   1227: #include <gsl/gsl_errno.h>
                   1228: #include <gsl/gsl_multimin.h>
                   1229: #endif
                   1230: 
1.167     brouard  1231: 
1.162     brouard  1232: #ifdef NLOPT
                   1233: #include <nlopt.h>
                   1234: typedef struct {
                   1235:   double (* function)(double [] );
                   1236: } myfunc_data ;
                   1237: #endif
                   1238: 
1.126     brouard  1239: /* #include <libintl.h> */
                   1240: /* #define _(String) gettext (String) */
                   1241: 
1.251     brouard  1242: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1243: 
                   1244: #define GNUPLOTPROGRAM "gnuplot"
                   1245: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1246: #define FILENAMELENGTH 256
1.126     brouard  1247: 
                   1248: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1249: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1250: 
1.144     brouard  1251: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1252: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1253: 
                   1254: #define NINTERVMAX 8
1.144     brouard  1255: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1256: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1257: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1258: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1259: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1260: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1261: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1262: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1263: /* #define AGESUP 130 */
1.288     brouard  1264: /* #define AGESUP 150 */
                   1265: #define AGESUP 200
1.268     brouard  1266: #define AGEINF 0
1.218     brouard  1267: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1268: #define AGEBASE 40
1.194     brouard  1269: #define AGEOVERFLOW 1.e20
1.164     brouard  1270: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1271: #ifdef _WIN32
                   1272: #define DIRSEPARATOR '\\'
                   1273: #define CHARSEPARATOR "\\"
                   1274: #define ODIRSEPARATOR '/'
                   1275: #else
1.126     brouard  1276: #define DIRSEPARATOR '/'
                   1277: #define CHARSEPARATOR "/"
                   1278: #define ODIRSEPARATOR '\\'
                   1279: #endif
                   1280: 
1.334   ! brouard  1281: /* $Id: imach.c,v 1.333 2022/08/21 09:10:30 brouard Exp $ */
1.126     brouard  1282: /* $State: Exp $ */
1.196     brouard  1283: #include "version.h"
                   1284: char version[]=__IMACH_VERSION__;
1.332     brouard  1285: 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.334   ! brouard  1286: char fullversion[]="$Revision: 1.333 $ $Date: 2022/08/21 09:10:30 $"; 
1.126     brouard  1287: char strstart[80];
                   1288: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1289: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1290: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1291: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1292: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1293: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age */
                   1294: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1295: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
1.225     brouard  1296: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1297: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1298: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.334   ! brouard  1299: int cptcoveff=0; /* Total number of single dummy covariates to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1300: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1301: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1302: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1303: int nsd=0; /**< Total number of single dummy variables (output) */
                   1304: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1305: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1306: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1307: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1308: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1309: int cptcov=0; /* Working variable */
1.334   ! brouard  1310: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1311: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1312: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1313: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1314: int nlstate=2; /* Number of live states */
                   1315: int ndeath=1; /* Number of dead states */
1.130     brouard  1316: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1317: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1318: int popbased=0;
                   1319: 
                   1320: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1321: int maxwav=0; /* Maxim number of waves */
                   1322: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1323: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1324: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1325:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1326: int mle=1, weightopt=0;
1.126     brouard  1327: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1328: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1329: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1330:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1331: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1332: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1333: 
1.130     brouard  1334: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1335: double **matprod2(); /* test */
1.126     brouard  1336: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1337: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1338: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1339: 
1.136     brouard  1340: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1341: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1342: FILE *ficlog, *ficrespow;
1.130     brouard  1343: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1344: double fretone; /* Only one call to likelihood */
1.130     brouard  1345: long ipmx=0; /* Number of contributions */
1.126     brouard  1346: double sw; /* Sum of weights */
                   1347: char filerespow[FILENAMELENGTH];
                   1348: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1349: FILE *ficresilk;
                   1350: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1351: FILE *ficresprobmorprev;
                   1352: FILE *fichtm, *fichtmcov; /* Html File */
                   1353: FILE *ficreseij;
                   1354: char filerese[FILENAMELENGTH];
                   1355: FILE *ficresstdeij;
                   1356: char fileresstde[FILENAMELENGTH];
                   1357: FILE *ficrescveij;
                   1358: char filerescve[FILENAMELENGTH];
                   1359: FILE  *ficresvij;
                   1360: char fileresv[FILENAMELENGTH];
1.269     brouard  1361: 
1.126     brouard  1362: char title[MAXLINE];
1.234     brouard  1363: char model[MAXLINE]; /**< The model line */
1.217     brouard  1364: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1365: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1366: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1367: char command[FILENAMELENGTH];
                   1368: int  outcmd=0;
                   1369: 
1.217     brouard  1370: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1371: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1372: char filelog[FILENAMELENGTH]; /* Log file */
                   1373: char filerest[FILENAMELENGTH];
                   1374: char fileregp[FILENAMELENGTH];
                   1375: char popfile[FILENAMELENGTH];
                   1376: 
                   1377: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1378: 
1.157     brouard  1379: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1380: /* struct timezone tzp; */
                   1381: /* extern int gettimeofday(); */
                   1382: struct tm tml, *gmtime(), *localtime();
                   1383: 
                   1384: extern time_t time();
                   1385: 
                   1386: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1387: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1388: struct tm tm;
                   1389: 
1.126     brouard  1390: char strcurr[80], strfor[80];
                   1391: 
                   1392: char *endptr;
                   1393: long lval;
                   1394: double dval;
                   1395: 
                   1396: #define NR_END 1
                   1397: #define FREE_ARG char*
                   1398: #define FTOL 1.0e-10
                   1399: 
                   1400: #define NRANSI 
1.240     brouard  1401: #define ITMAX 200
                   1402: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1403: 
                   1404: #define TOL 2.0e-4 
                   1405: 
                   1406: #define CGOLD 0.3819660 
                   1407: #define ZEPS 1.0e-10 
                   1408: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1409: 
                   1410: #define GOLD 1.618034 
                   1411: #define GLIMIT 100.0 
                   1412: #define TINY 1.0e-20 
                   1413: 
                   1414: static double maxarg1,maxarg2;
                   1415: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1416: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1417:   
                   1418: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1419: #define rint(a) floor(a+0.5)
1.166     brouard  1420: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1421: #define mytinydouble 1.0e-16
1.166     brouard  1422: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1423: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1424: /* static double dsqrarg; */
                   1425: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1426: static double sqrarg;
                   1427: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1428: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1429: int agegomp= AGEGOMP;
                   1430: 
                   1431: int imx; 
                   1432: int stepm=1;
                   1433: /* Stepm, step in month: minimum step interpolation*/
                   1434: 
                   1435: int estepm;
                   1436: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1437: 
                   1438: int m,nb;
                   1439: long *num;
1.197     brouard  1440: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1441: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1442:                   covariate for which somebody answered excluding 
                   1443:                   undefined. Usually 2: 0 and 1. */
                   1444: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1445:                             covariate for which somebody answered including 
                   1446:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1447: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1448: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1449: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1450: 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  1451: double *ageexmed,*agecens;
                   1452: double dateintmean=0;
1.296     brouard  1453:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1454:   double anprojf, mprojf, jprojf;
1.126     brouard  1455: 
1.296     brouard  1456:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1457:   double anbackf, mbackf, jbackf;
                   1458:   double jintmean,mintmean,aintmean;  
1.126     brouard  1459: double *weight;
                   1460: int **s; /* Status */
1.141     brouard  1461: double *agedc;
1.145     brouard  1462: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1463:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1464:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1465: double **coqvar; /* Fixed quantitative covariate nqv */
                   1466: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1467: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1468: double  idx; 
                   1469: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1470: /* Some documentation */
                   1471:       /*   Design original data
                   1472:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1473:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1474:        *                                                             ntv=3     nqtv=1
1.330     brouard  1475:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1476:        * For time varying covariate, quanti or dummies
                   1477:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1478:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1479:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1480:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1481:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1482:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1483:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1484:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1485:        */
                   1486: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1487: /* 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
                   1488:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1489:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1490: */
1.319     brouard  1491: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1492: /*    k        1  2   3   4     5    6    7     8    9 */
                   1493: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1494:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1495:                                                          /* product */
                   1496: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1497:                                                          /*(single or product without age), 2 dummy*/
                   1498:                                                          /* with age product, 3 quant with age product*/
                   1499: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1500: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1501: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1502: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1503: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1504: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1505: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1506: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1507: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1508: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1509: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1510: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1511: /* 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  1512: /* 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  1513: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1514: /* Type                    */
                   1515: /* V         1  2  3  4  5 */
                   1516: /*           F  F  V  V  V */
                   1517: /*           D  Q  D  D  Q */
                   1518: /*                         */
                   1519: int *TvarsD;
1.330     brouard  1520: int *TnsdVar;
1.234     brouard  1521: int *TvarsDind;
                   1522: int *TvarsQ;
                   1523: int *TvarsQind;
                   1524: 
1.318     brouard  1525: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1526: int nresult=0;
1.258     brouard  1527: int parameterline=0; /* # of the parameter (type) line */
1.334   ! brouard  1528: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
        !          1529: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
        !          1530: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
        !          1531: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1532: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1533: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334   ! brouard  1534: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1535: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1536: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1537: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1538: 
                   1539: /* 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
                   1540:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1541:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1542: */
1.234     brouard  1543: /* 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  1544: 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 */
                   1545: 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 */
                   1546: 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 */
                   1547: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1548: 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 */
                   1549: 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  1550: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1551: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1552: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1553: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1554: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1555: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1556: 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 */
                   1557: 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 */
                   1558: 
1.230     brouard  1559: int *Tvarsel; /**< Selected covariates for output */
                   1560: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1561: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1562: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1563: 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  1564: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1565: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1566: int *Tage;
1.227     brouard  1567: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1568: 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  1569: 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*/ 
                   1570: 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  1571: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1572: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1573: int **Tvard;
1.330     brouard  1574: int **Tvardk;
1.227     brouard  1575: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1576: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1577: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1578:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1579:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1580: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1581: double *lsurv, *lpop, *tpop;
                   1582: 
1.231     brouard  1583: #define FD 1; /* Fixed dummy covariate */
                   1584: #define FQ 2; /* Fixed quantitative covariate */
                   1585: #define FP 3; /* Fixed product covariate */
                   1586: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1587: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1588: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1589: #define VD 10; /* Varying dummy covariate */
                   1590: #define VQ 11; /* Varying quantitative covariate */
                   1591: #define VP 12; /* Varying product covariate */
                   1592: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1593: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1594: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1595: #define APFD 16; /* Age product * fixed dummy covariate */
                   1596: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1597: #define APVD 18; /* Age product * varying dummy covariate */
                   1598: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1599: 
                   1600: #define FTYPE 1; /* Fixed covariate */
                   1601: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1602: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1603: 
                   1604: struct kmodel{
                   1605:        int maintype; /* main type */
                   1606:        int subtype; /* subtype */
                   1607: };
                   1608: struct kmodel modell[NCOVMAX];
                   1609: 
1.143     brouard  1610: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1611: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1612: 
                   1613: /**************** split *************************/
                   1614: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1615: {
                   1616:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1617:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1618:   */ 
                   1619:   char *ss;                            /* pointer */
1.186     brouard  1620:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1621: 
                   1622:   l1 = strlen(path );                  /* length of path */
                   1623:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1624:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1625:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1626:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1627:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1628:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1629:     /* get current working directory */
                   1630:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1631: #ifdef WIN32
                   1632:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1633: #else
                   1634:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1635: #endif
1.126     brouard  1636:       return( GLOCK_ERROR_GETCWD );
                   1637:     }
                   1638:     /* got dirc from getcwd*/
                   1639:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1640:   } else {                             /* strip directory from path */
1.126     brouard  1641:     ss++;                              /* after this, the filename */
                   1642:     l2 = strlen( ss );                 /* length of filename */
                   1643:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1644:     strcpy( name, ss );                /* save file name */
                   1645:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1646:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1647:     printf(" DIRC2 = %s \n",dirc);
                   1648:   }
                   1649:   /* We add a separator at the end of dirc if not exists */
                   1650:   l1 = strlen( dirc );                 /* length of directory */
                   1651:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1652:     dirc[l1] =  DIRSEPARATOR;
                   1653:     dirc[l1+1] = 0; 
                   1654:     printf(" DIRC3 = %s \n",dirc);
                   1655:   }
                   1656:   ss = strrchr( name, '.' );           /* find last / */
                   1657:   if (ss >0){
                   1658:     ss++;
                   1659:     strcpy(ext,ss);                    /* save extension */
                   1660:     l1= strlen( name);
                   1661:     l2= strlen(ss)+1;
                   1662:     strncpy( finame, name, l1-l2);
                   1663:     finame[l1-l2]= 0;
                   1664:   }
                   1665: 
                   1666:   return( 0 );                         /* we're done */
                   1667: }
                   1668: 
                   1669: 
                   1670: /******************************************/
                   1671: 
                   1672: void replace_back_to_slash(char *s, char*t)
                   1673: {
                   1674:   int i;
                   1675:   int lg=0;
                   1676:   i=0;
                   1677:   lg=strlen(t);
                   1678:   for(i=0; i<= lg; i++) {
                   1679:     (s[i] = t[i]);
                   1680:     if (t[i]== '\\') s[i]='/';
                   1681:   }
                   1682: }
                   1683: 
1.132     brouard  1684: char *trimbb(char *out, char *in)
1.137     brouard  1685: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1686:   char *s;
                   1687:   s=out;
                   1688:   while (*in != '\0'){
1.137     brouard  1689:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1690:       in++;
                   1691:     }
                   1692:     *out++ = *in++;
                   1693:   }
                   1694:   *out='\0';
                   1695:   return s;
                   1696: }
                   1697: 
1.187     brouard  1698: /* char *substrchaine(char *out, char *in, char *chain) */
                   1699: /* { */
                   1700: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1701: /*   char *s, *t; */
                   1702: /*   t=in;s=out; */
                   1703: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1704: /*     *out++ = *in++; */
                   1705: /*   } */
                   1706: 
                   1707: /*   /\* *in matches *chain *\/ */
                   1708: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1709: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1710: /*   } */
                   1711: /*   in--; chain--; */
                   1712: /*   while ( (*in != '\0')){ */
                   1713: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1714: /*     *out++ = *in++; */
                   1715: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1716: /*   } */
                   1717: /*   *out='\0'; */
                   1718: /*   out=s; */
                   1719: /*   return out; */
                   1720: /* } */
                   1721: char *substrchaine(char *out, char *in, char *chain)
                   1722: {
                   1723:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1724:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1725: 
                   1726:   char *strloc;
                   1727: 
                   1728:   strcpy (out, in); 
                   1729:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1730:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1731:   if(strloc != NULL){ 
                   1732:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1733:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1734:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1735:   }
                   1736:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1737:   return out;
                   1738: }
                   1739: 
                   1740: 
1.145     brouard  1741: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1742: {
1.187     brouard  1743:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1744:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1745:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1746:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1747:   */
1.160     brouard  1748:   char *s, *t;
1.145     brouard  1749:   t=in;s=in;
                   1750:   while ((*in != occ) && (*in != '\0')){
                   1751:     *alocc++ = *in++;
                   1752:   }
                   1753:   if( *in == occ){
                   1754:     *(alocc)='\0';
                   1755:     s=++in;
                   1756:   }
                   1757:  
                   1758:   if (s == t) {/* occ not found */
                   1759:     *(alocc-(in-s))='\0';
                   1760:     in=s;
                   1761:   }
                   1762:   while ( *in != '\0'){
                   1763:     *blocc++ = *in++;
                   1764:   }
                   1765: 
                   1766:   *blocc='\0';
                   1767:   return t;
                   1768: }
1.137     brouard  1769: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1770: {
1.187     brouard  1771:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1772:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1773:      gives blocc="abcdef2ghi" and alocc="j".
                   1774:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1775:   */
                   1776:   char *s, *t;
                   1777:   t=in;s=in;
                   1778:   while (*in != '\0'){
                   1779:     while( *in == occ){
                   1780:       *blocc++ = *in++;
                   1781:       s=in;
                   1782:     }
                   1783:     *blocc++ = *in++;
                   1784:   }
                   1785:   if (s == t) /* occ not found */
                   1786:     *(blocc-(in-s))='\0';
                   1787:   else
                   1788:     *(blocc-(in-s)-1)='\0';
                   1789:   in=s;
                   1790:   while ( *in != '\0'){
                   1791:     *alocc++ = *in++;
                   1792:   }
                   1793: 
                   1794:   *alocc='\0';
                   1795:   return s;
                   1796: }
                   1797: 
1.126     brouard  1798: int nbocc(char *s, char occ)
                   1799: {
                   1800:   int i,j=0;
                   1801:   int lg=20;
                   1802:   i=0;
                   1803:   lg=strlen(s);
                   1804:   for(i=0; i<= lg; i++) {
1.234     brouard  1805:     if  (s[i] == occ ) j++;
1.126     brouard  1806:   }
                   1807:   return j;
                   1808: }
                   1809: 
1.137     brouard  1810: /* void cutv(char *u,char *v, char*t, char occ) */
                   1811: /* { */
                   1812: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1813: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1814: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1815: /*   int i,lg,j,p=0; */
                   1816: /*   i=0; */
                   1817: /*   lg=strlen(t); */
                   1818: /*   for(j=0; j<=lg-1; j++) { */
                   1819: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1820: /*   } */
1.126     brouard  1821: 
1.137     brouard  1822: /*   for(j=0; j<p; j++) { */
                   1823: /*     (u[j] = t[j]); */
                   1824: /*   } */
                   1825: /*      u[p]='\0'; */
1.126     brouard  1826: 
1.137     brouard  1827: /*    for(j=0; j<= lg; j++) { */
                   1828: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1829: /*   } */
                   1830: /* } */
1.126     brouard  1831: 
1.160     brouard  1832: #ifdef _WIN32
                   1833: char * strsep(char **pp, const char *delim)
                   1834: {
                   1835:   char *p, *q;
                   1836:          
                   1837:   if ((p = *pp) == NULL)
                   1838:     return 0;
                   1839:   if ((q = strpbrk (p, delim)) != NULL)
                   1840:   {
                   1841:     *pp = q + 1;
                   1842:     *q = '\0';
                   1843:   }
                   1844:   else
                   1845:     *pp = 0;
                   1846:   return p;
                   1847: }
                   1848: #endif
                   1849: 
1.126     brouard  1850: /********************** nrerror ********************/
                   1851: 
                   1852: void nrerror(char error_text[])
                   1853: {
                   1854:   fprintf(stderr,"ERREUR ...\n");
                   1855:   fprintf(stderr,"%s\n",error_text);
                   1856:   exit(EXIT_FAILURE);
                   1857: }
                   1858: /*********************** vector *******************/
                   1859: double *vector(int nl, int nh)
                   1860: {
                   1861:   double *v;
                   1862:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1863:   if (!v) nrerror("allocation failure in vector");
                   1864:   return v-nl+NR_END;
                   1865: }
                   1866: 
                   1867: /************************ free vector ******************/
                   1868: void free_vector(double*v, int nl, int nh)
                   1869: {
                   1870:   free((FREE_ARG)(v+nl-NR_END));
                   1871: }
                   1872: 
                   1873: /************************ivector *******************************/
                   1874: int *ivector(long nl,long nh)
                   1875: {
                   1876:   int *v;
                   1877:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1878:   if (!v) nrerror("allocation failure in ivector");
                   1879:   return v-nl+NR_END;
                   1880: }
                   1881: 
                   1882: /******************free ivector **************************/
                   1883: void free_ivector(int *v, long nl, long nh)
                   1884: {
                   1885:   free((FREE_ARG)(v+nl-NR_END));
                   1886: }
                   1887: 
                   1888: /************************lvector *******************************/
                   1889: long *lvector(long nl,long nh)
                   1890: {
                   1891:   long *v;
                   1892:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1893:   if (!v) nrerror("allocation failure in ivector");
                   1894:   return v-nl+NR_END;
                   1895: }
                   1896: 
                   1897: /******************free lvector **************************/
                   1898: void free_lvector(long *v, long nl, long nh)
                   1899: {
                   1900:   free((FREE_ARG)(v+nl-NR_END));
                   1901: }
                   1902: 
                   1903: /******************* imatrix *******************************/
                   1904: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1905:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1906: { 
                   1907:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1908:   int **m; 
                   1909:   
                   1910:   /* allocate pointers to rows */ 
                   1911:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1912:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1913:   m += NR_END; 
                   1914:   m -= nrl; 
                   1915:   
                   1916:   
                   1917:   /* allocate rows and set pointers to them */ 
                   1918:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1919:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1920:   m[nrl] += NR_END; 
                   1921:   m[nrl] -= ncl; 
                   1922:   
                   1923:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1924:   
                   1925:   /* return pointer to array of pointers to rows */ 
                   1926:   return m; 
                   1927: } 
                   1928: 
                   1929: /****************** free_imatrix *************************/
                   1930: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1931:       int **m;
                   1932:       long nch,ncl,nrh,nrl; 
                   1933:      /* free an int matrix allocated by imatrix() */ 
                   1934: { 
                   1935:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1936:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1937: } 
                   1938: 
                   1939: /******************* matrix *******************************/
                   1940: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1941: {
                   1942:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1943:   double **m;
                   1944: 
                   1945:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1946:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1947:   m += NR_END;
                   1948:   m -= nrl;
                   1949: 
                   1950:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1951:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1952:   m[nrl] += NR_END;
                   1953:   m[nrl] -= ncl;
                   1954: 
                   1955:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1956:   return m;
1.145     brouard  1957:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1958: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1959: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1960:    */
                   1961: }
                   1962: 
                   1963: /*************************free matrix ************************/
                   1964: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1965: {
                   1966:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1967:   free((FREE_ARG)(m+nrl-NR_END));
                   1968: }
                   1969: 
                   1970: /******************* ma3x *******************************/
                   1971: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1972: {
                   1973:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1974:   double ***m;
                   1975: 
                   1976:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1977:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1978:   m += NR_END;
                   1979:   m -= nrl;
                   1980: 
                   1981:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1982:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1983:   m[nrl] += NR_END;
                   1984:   m[nrl] -= ncl;
                   1985: 
                   1986:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1987: 
                   1988:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1989:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1990:   m[nrl][ncl] += NR_END;
                   1991:   m[nrl][ncl] -= nll;
                   1992:   for (j=ncl+1; j<=nch; j++) 
                   1993:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1994:   
                   1995:   for (i=nrl+1; i<=nrh; i++) {
                   1996:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1997:     for (j=ncl+1; j<=nch; j++) 
                   1998:       m[i][j]=m[i][j-1]+nlay;
                   1999:   }
                   2000:   return m; 
                   2001:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2002:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2003:   */
                   2004: }
                   2005: 
                   2006: /*************************free ma3x ************************/
                   2007: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2008: {
                   2009:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2010:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2011:   free((FREE_ARG)(m+nrl-NR_END));
                   2012: }
                   2013: 
                   2014: /*************** function subdirf ***********/
                   2015: char *subdirf(char fileres[])
                   2016: {
                   2017:   /* Caution optionfilefiname is hidden */
                   2018:   strcpy(tmpout,optionfilefiname);
                   2019:   strcat(tmpout,"/"); /* Add to the right */
                   2020:   strcat(tmpout,fileres);
                   2021:   return tmpout;
                   2022: }
                   2023: 
                   2024: /*************** function subdirf2 ***********/
                   2025: char *subdirf2(char fileres[], char *preop)
                   2026: {
1.314     brouard  2027:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2028:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2029:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2030:   /* Caution optionfilefiname is hidden */
                   2031:   strcpy(tmpout,optionfilefiname);
                   2032:   strcat(tmpout,"/");
                   2033:   strcat(tmpout,preop);
                   2034:   strcat(tmpout,fileres);
                   2035:   return tmpout;
                   2036: }
                   2037: 
                   2038: /*************** function subdirf3 ***********/
                   2039: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2040: {
                   2041:   
                   2042:   /* Caution optionfilefiname is hidden */
                   2043:   strcpy(tmpout,optionfilefiname);
                   2044:   strcat(tmpout,"/");
                   2045:   strcat(tmpout,preop);
                   2046:   strcat(tmpout,preop2);
                   2047:   strcat(tmpout,fileres);
                   2048:   return tmpout;
                   2049: }
1.213     brouard  2050:  
                   2051: /*************** function subdirfext ***********/
                   2052: char *subdirfext(char fileres[], char *preop, char *postop)
                   2053: {
                   2054:   
                   2055:   strcpy(tmpout,preop);
                   2056:   strcat(tmpout,fileres);
                   2057:   strcat(tmpout,postop);
                   2058:   return tmpout;
                   2059: }
1.126     brouard  2060: 
1.213     brouard  2061: /*************** function subdirfext3 ***********/
                   2062: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2063: {
                   2064:   
                   2065:   /* Caution optionfilefiname is hidden */
                   2066:   strcpy(tmpout,optionfilefiname);
                   2067:   strcat(tmpout,"/");
                   2068:   strcat(tmpout,preop);
                   2069:   strcat(tmpout,fileres);
                   2070:   strcat(tmpout,postop);
                   2071:   return tmpout;
                   2072: }
                   2073:  
1.162     brouard  2074: char *asc_diff_time(long time_sec, char ascdiff[])
                   2075: {
                   2076:   long sec_left, days, hours, minutes;
                   2077:   days = (time_sec) / (60*60*24);
                   2078:   sec_left = (time_sec) % (60*60*24);
                   2079:   hours = (sec_left) / (60*60) ;
                   2080:   sec_left = (sec_left) %(60*60);
                   2081:   minutes = (sec_left) /60;
                   2082:   sec_left = (sec_left) % (60);
                   2083:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2084:   return ascdiff;
                   2085: }
                   2086: 
1.126     brouard  2087: /***************** f1dim *************************/
                   2088: extern int ncom; 
                   2089: extern double *pcom,*xicom;
                   2090: extern double (*nrfunc)(double []); 
                   2091:  
                   2092: double f1dim(double x) 
                   2093: { 
                   2094:   int j; 
                   2095:   double f;
                   2096:   double *xt; 
                   2097:  
                   2098:   xt=vector(1,ncom); 
                   2099:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2100:   f=(*nrfunc)(xt); 
                   2101:   free_vector(xt,1,ncom); 
                   2102:   return f; 
                   2103: } 
                   2104: 
                   2105: /*****************brent *************************/
                   2106: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2107: {
                   2108:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2109:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2110:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2111:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2112:    * returned function value. 
                   2113:   */
1.126     brouard  2114:   int iter; 
                   2115:   double a,b,d,etemp;
1.159     brouard  2116:   double fu=0,fv,fw,fx;
1.164     brouard  2117:   double ftemp=0.;
1.126     brouard  2118:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2119:   double e=0.0; 
                   2120:  
                   2121:   a=(ax < cx ? ax : cx); 
                   2122:   b=(ax > cx ? ax : cx); 
                   2123:   x=w=v=bx; 
                   2124:   fw=fv=fx=(*f)(x); 
                   2125:   for (iter=1;iter<=ITMAX;iter++) { 
                   2126:     xm=0.5*(a+b); 
                   2127:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2128:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2129:     printf(".");fflush(stdout);
                   2130:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2131: #ifdef DEBUGBRENT
1.126     brouard  2132:     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);
                   2133:     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);
                   2134:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2135: #endif
                   2136:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2137:       *xmin=x; 
                   2138:       return fx; 
                   2139:     } 
                   2140:     ftemp=fu;
                   2141:     if (fabs(e) > tol1) { 
                   2142:       r=(x-w)*(fx-fv); 
                   2143:       q=(x-v)*(fx-fw); 
                   2144:       p=(x-v)*q-(x-w)*r; 
                   2145:       q=2.0*(q-r); 
                   2146:       if (q > 0.0) p = -p; 
                   2147:       q=fabs(q); 
                   2148:       etemp=e; 
                   2149:       e=d; 
                   2150:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2151:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2152:       else { 
1.224     brouard  2153:                                d=p/q; 
                   2154:                                u=x+d; 
                   2155:                                if (u-a < tol2 || b-u < tol2) 
                   2156:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2157:       } 
                   2158:     } else { 
                   2159:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2160:     } 
                   2161:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2162:     fu=(*f)(u); 
                   2163:     if (fu <= fx) { 
                   2164:       if (u >= x) a=x; else b=x; 
                   2165:       SHFT(v,w,x,u) 
1.183     brouard  2166:       SHFT(fv,fw,fx,fu) 
                   2167:     } else { 
                   2168:       if (u < x) a=u; else b=u; 
                   2169:       if (fu <= fw || w == x) { 
1.224     brouard  2170:                                v=w; 
                   2171:                                w=u; 
                   2172:                                fv=fw; 
                   2173:                                fw=fu; 
1.183     brouard  2174:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2175:                                v=u; 
                   2176:                                fv=fu; 
1.183     brouard  2177:       } 
                   2178:     } 
1.126     brouard  2179:   } 
                   2180:   nrerror("Too many iterations in brent"); 
                   2181:   *xmin=x; 
                   2182:   return fx; 
                   2183: } 
                   2184: 
                   2185: /****************** mnbrak ***********************/
                   2186: 
                   2187: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2188:            double (*func)(double)) 
1.183     brouard  2189: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2190: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2191: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2192: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2193:    */
1.126     brouard  2194:   double ulim,u,r,q, dum;
                   2195:   double fu; 
1.187     brouard  2196: 
                   2197:   double scale=10.;
                   2198:   int iterscale=0;
                   2199: 
                   2200:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2201:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2202: 
                   2203: 
                   2204:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2205:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2206:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2207:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2208:   /* } */
                   2209: 
1.126     brouard  2210:   if (*fb > *fa) { 
                   2211:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2212:     SHFT(dum,*fb,*fa,dum) 
                   2213:   } 
1.126     brouard  2214:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2215:   *fc=(*func)(*cx); 
1.183     brouard  2216: #ifdef DEBUG
1.224     brouard  2217:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2218:   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  2219: #endif
1.224     brouard  2220:   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  2221:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2222:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2223:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2224:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2225:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2226:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2227:       fu=(*func)(u); 
1.163     brouard  2228: #ifdef DEBUG
                   2229:       /* f(x)=A(x-u)**2+f(u) */
                   2230:       double A, fparabu; 
                   2231:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2232:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2233:       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);
                   2234:       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  2235:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2236:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2237:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2238:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2239: #endif 
1.184     brouard  2240: #ifdef MNBRAKORIGINAL
1.183     brouard  2241: #else
1.191     brouard  2242: /*       if (fu > *fc) { */
                   2243: /* #ifdef DEBUG */
                   2244: /*       printf("mnbrak4  fu > fc \n"); */
                   2245: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2246: /* #endif */
                   2247: /*     /\* 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 *\\/  *\/ */
                   2248: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2249: /*     dum=u; /\* Shifting c and u *\/ */
                   2250: /*     u = *cx; */
                   2251: /*     *cx = dum; */
                   2252: /*     dum = fu; */
                   2253: /*     fu = *fc; */
                   2254: /*     *fc =dum; */
                   2255: /*       } else { /\* end *\/ */
                   2256: /* #ifdef DEBUG */
                   2257: /*       printf("mnbrak3  fu < fc \n"); */
                   2258: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2259: /* #endif */
                   2260: /*     dum=u; /\* Shifting c and u *\/ */
                   2261: /*     u = *cx; */
                   2262: /*     *cx = dum; */
                   2263: /*     dum = fu; */
                   2264: /*     fu = *fc; */
                   2265: /*     *fc =dum; */
                   2266: /*       } */
1.224     brouard  2267: #ifdef DEBUGMNBRAK
                   2268:                 double A, fparabu; 
                   2269:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2270:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2271:      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);
                   2272:      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  2273: #endif
1.191     brouard  2274:       dum=u; /* Shifting c and u */
                   2275:       u = *cx;
                   2276:       *cx = dum;
                   2277:       dum = fu;
                   2278:       fu = *fc;
                   2279:       *fc =dum;
1.183     brouard  2280: #endif
1.162     brouard  2281:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2282: #ifdef DEBUG
1.224     brouard  2283:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2284:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2285: #endif
1.126     brouard  2286:       fu=(*func)(u); 
                   2287:       if (fu < *fc) { 
1.183     brouard  2288: #ifdef DEBUG
1.224     brouard  2289:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2290:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2291: #endif
                   2292:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2293:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2294: #ifdef DEBUG
                   2295:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2296: #endif
                   2297:       } 
1.162     brouard  2298:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2299: #ifdef DEBUG
1.224     brouard  2300:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2301:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2302: #endif
1.126     brouard  2303:       u=ulim; 
                   2304:       fu=(*func)(u); 
1.183     brouard  2305:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2306: #ifdef DEBUG
1.224     brouard  2307:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2308:       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  2309: #endif
1.126     brouard  2310:       u=(*cx)+GOLD*(*cx-*bx); 
                   2311:       fu=(*func)(u); 
1.224     brouard  2312: #ifdef DEBUG
                   2313:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2314:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2315: #endif
1.183     brouard  2316:     } /* end tests */
1.126     brouard  2317:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2318:     SHFT(*fa,*fb,*fc,fu) 
                   2319: #ifdef DEBUG
1.224     brouard  2320:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2321:       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  2322: #endif
                   2323:   } /* 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  2324: } 
                   2325: 
                   2326: /*************** linmin ************************/
1.162     brouard  2327: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2328: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2329: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2330: the value of func at the returned location p . This is actually all accomplished by calling the
                   2331: routines mnbrak and brent .*/
1.126     brouard  2332: int ncom; 
                   2333: double *pcom,*xicom;
                   2334: double (*nrfunc)(double []); 
                   2335:  
1.224     brouard  2336: #ifdef LINMINORIGINAL
1.126     brouard  2337: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2338: #else
                   2339: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2340: #endif
1.126     brouard  2341: { 
                   2342:   double brent(double ax, double bx, double cx, 
                   2343:               double (*f)(double), double tol, double *xmin); 
                   2344:   double f1dim(double x); 
                   2345:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2346:              double *fc, double (*func)(double)); 
                   2347:   int j; 
                   2348:   double xx,xmin,bx,ax; 
                   2349:   double fx,fb,fa;
1.187     brouard  2350: 
1.203     brouard  2351: #ifdef LINMINORIGINAL
                   2352: #else
                   2353:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2354: #endif
                   2355:   
1.126     brouard  2356:   ncom=n; 
                   2357:   pcom=vector(1,n); 
                   2358:   xicom=vector(1,n); 
                   2359:   nrfunc=func; 
                   2360:   for (j=1;j<=n;j++) { 
                   2361:     pcom[j]=p[j]; 
1.202     brouard  2362:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2363:   } 
1.187     brouard  2364: 
1.203     brouard  2365: #ifdef LINMINORIGINAL
                   2366:   xx=1.;
                   2367: #else
                   2368:   axs=0.0;
                   2369:   xxs=1.;
                   2370:   do{
                   2371:     xx= xxs;
                   2372: #endif
1.187     brouard  2373:     ax=0.;
                   2374:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2375:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2376:     /* 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))   */
                   2377:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2378:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2379:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2380:     /* 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  2381: #ifdef LINMINORIGINAL
                   2382: #else
                   2383:     if (fx != fx){
1.224     brouard  2384:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2385:                        printf("|");
                   2386:                        fprintf(ficlog,"|");
1.203     brouard  2387: #ifdef DEBUGLINMIN
1.224     brouard  2388:                        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  2389: #endif
                   2390:     }
1.224     brouard  2391:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2392: #endif
                   2393:   
1.191     brouard  2394: #ifdef DEBUGLINMIN
                   2395:   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  2396:   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  2397: #endif
1.224     brouard  2398: #ifdef LINMINORIGINAL
                   2399: #else
1.317     brouard  2400:   if(fb == fx){ /* Flat function in the direction */
                   2401:     xmin=xx;
1.224     brouard  2402:     *flat=1;
1.317     brouard  2403:   }else{
1.224     brouard  2404:     *flat=0;
                   2405: #endif
                   2406:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2407:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2408:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2409:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2410:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2411:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2412: #ifdef DEBUG
1.224     brouard  2413:   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);
                   2414:   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);
                   2415: #endif
                   2416: #ifdef LINMINORIGINAL
                   2417: #else
                   2418:                        }
1.126     brouard  2419: #endif
1.191     brouard  2420: #ifdef DEBUGLINMIN
                   2421:   printf("linmin end ");
1.202     brouard  2422:   fprintf(ficlog,"linmin end ");
1.191     brouard  2423: #endif
1.126     brouard  2424:   for (j=1;j<=n;j++) { 
1.203     brouard  2425: #ifdef LINMINORIGINAL
                   2426:     xi[j] *= xmin; 
                   2427: #else
                   2428: #ifdef DEBUGLINMIN
                   2429:     if(xxs <1.0)
                   2430:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2431: #endif
                   2432:     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) */
                   2433: #ifdef DEBUGLINMIN
                   2434:     if(xxs <1.0)
                   2435:       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 );
                   2436: #endif
                   2437: #endif
1.187     brouard  2438:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2439:   } 
1.191     brouard  2440: #ifdef DEBUGLINMIN
1.203     brouard  2441:   printf("\n");
1.191     brouard  2442:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2443:   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  2444:   for (j=1;j<=n;j++) { 
1.202     brouard  2445:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2446:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2447:     if(j % ncovmodel == 0){
1.191     brouard  2448:       printf("\n");
1.202     brouard  2449:       fprintf(ficlog,"\n");
                   2450:     }
1.191     brouard  2451:   }
1.203     brouard  2452: #else
1.191     brouard  2453: #endif
1.126     brouard  2454:   free_vector(xicom,1,n); 
                   2455:   free_vector(pcom,1,n); 
                   2456: } 
                   2457: 
                   2458: 
                   2459: /*************** powell ************************/
1.162     brouard  2460: /*
1.317     brouard  2461: Minimization of a function func of n variables. Input consists in an initial starting point
                   2462: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2463: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2464: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2465: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2466: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2467:  */
1.224     brouard  2468: #ifdef LINMINORIGINAL
                   2469: #else
                   2470:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2471:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2472: #endif
1.126     brouard  2473: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2474:            double (*func)(double [])) 
                   2475: { 
1.224     brouard  2476: #ifdef LINMINORIGINAL
                   2477:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2478:              double (*func)(double [])); 
1.224     brouard  2479: #else 
1.241     brouard  2480:  void linmin(double p[], double xi[], int n, double *fret,
                   2481:             double (*func)(double []),int *flat); 
1.224     brouard  2482: #endif
1.239     brouard  2483:  int i,ibig,j,jk,k; 
1.126     brouard  2484:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2485:   double directest;
1.126     brouard  2486:   double fp,fptt;
                   2487:   double *xits;
                   2488:   int niterf, itmp;
                   2489: 
                   2490:   pt=vector(1,n); 
                   2491:   ptt=vector(1,n); 
                   2492:   xit=vector(1,n); 
                   2493:   xits=vector(1,n); 
                   2494:   *fret=(*func)(p); 
                   2495:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2496:   rcurr_time = time(NULL);  
1.126     brouard  2497:   for (*iter=1;;++(*iter)) { 
                   2498:     ibig=0; 
                   2499:     del=0.0; 
1.157     brouard  2500:     rlast_time=rcurr_time;
                   2501:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2502:     rcurr_time = time(NULL);  
                   2503:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2504:     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);
                   2505:     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  2506: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2507:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2508:     for (i=1;i<=n;i++) {
1.126     brouard  2509:       fprintf(ficrespow," %.12lf", p[i]);
                   2510:     }
1.239     brouard  2511:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2512:     printf("\n#model=  1      +     age ");
                   2513:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2514:     if(nagesqr==1){
1.241     brouard  2515:        printf("  + age*age  ");
                   2516:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2517:     }
                   2518:     for(j=1;j <=ncovmodel-2;j++){
                   2519:       if(Typevar[j]==0) {
                   2520:        printf("  +      V%d  ",Tvar[j]);
                   2521:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2522:       }else if(Typevar[j]==1) {
                   2523:        printf("  +    V%d*age ",Tvar[j]);
                   2524:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2525:       }else if(Typevar[j]==2) {
                   2526:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2527:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2528:       }
                   2529:     }
1.126     brouard  2530:     printf("\n");
1.239     brouard  2531: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2532: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2533:     fprintf(ficlog,"\n");
1.239     brouard  2534:     for(i=1,jk=1; i <=nlstate; i++){
                   2535:       for(k=1; k <=(nlstate+ndeath); k++){
                   2536:        if (k != i) {
                   2537:          printf("%d%d ",i,k);
                   2538:          fprintf(ficlog,"%d%d ",i,k);
                   2539:          for(j=1; j <=ncovmodel; j++){
                   2540:            printf("%12.7f ",p[jk]);
                   2541:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2542:            jk++; 
                   2543:          }
                   2544:          printf("\n");
                   2545:          fprintf(ficlog,"\n");
                   2546:        }
                   2547:       }
                   2548:     }
1.241     brouard  2549:     if(*iter <=3 && *iter >1){
1.157     brouard  2550:       tml = *localtime(&rcurr_time);
                   2551:       strcpy(strcurr,asctime(&tml));
                   2552:       rforecast_time=rcurr_time; 
1.126     brouard  2553:       itmp = strlen(strcurr);
                   2554:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2555:        strcurr[itmp-1]='\0';
1.162     brouard  2556:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2557:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2558:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2559:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2560:        forecast_time = *localtime(&rforecast_time);
                   2561:        strcpy(strfor,asctime(&forecast_time));
                   2562:        itmp = strlen(strfor);
                   2563:        if(strfor[itmp-1]=='\n')
                   2564:          strfor[itmp-1]='\0';
                   2565:        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);
                   2566:        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  2567:       }
                   2568:     }
1.187     brouard  2569:     for (i=1;i<=n;i++) { /* For each direction i */
                   2570:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2571:       fptt=(*fret); 
                   2572: #ifdef DEBUG
1.203     brouard  2573:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2574:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2575: #endif
1.203     brouard  2576:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2577:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2578: #ifdef LINMINORIGINAL
1.188     brouard  2579:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2580: #else
                   2581:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2582:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2583: #endif
                   2584:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2585:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2586:                                /* because that direction will be replaced unless the gain del is small */
                   2587:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2588:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2589:                                /* with the new direction. */
                   2590:                                del=fabs(fptt-(*fret)); 
                   2591:                                ibig=i; 
1.126     brouard  2592:       } 
                   2593: #ifdef DEBUG
                   2594:       printf("%d %.12e",i,(*fret));
                   2595:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2596:       for (j=1;j<=n;j++) {
1.224     brouard  2597:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2598:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2599:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2600:       }
                   2601:       for(j=1;j<=n;j++) {
1.225     brouard  2602:                                printf(" p(%d)=%.12e",j,p[j]);
                   2603:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2604:       }
                   2605:       printf("\n");
                   2606:       fprintf(ficlog,"\n");
                   2607: #endif
1.187     brouard  2608:     } /* end loop on each direction i */
                   2609:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2610:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2611:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2612:     for(j=1;j<=n;j++) {
                   2613:       if(flatdir[j] >0){
                   2614:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2615:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2616:       }
1.319     brouard  2617:       /* printf("\n"); */
                   2618:       /* fprintf(ficlog,"\n"); */
                   2619:     }
1.243     brouard  2620:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2621:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2622:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2623:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2624:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2625:       /* decreased of more than 3.84  */
                   2626:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2627:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2628:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2629:                        
1.188     brouard  2630:       /* Starting the program with initial values given by a former maximization will simply change */
                   2631:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2632:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2633:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2634: #ifdef DEBUG
                   2635:       int k[2],l;
                   2636:       k[0]=1;
                   2637:       k[1]=-1;
                   2638:       printf("Max: %.12e",(*func)(p));
                   2639:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2640:       for (j=1;j<=n;j++) {
                   2641:        printf(" %.12e",p[j]);
                   2642:        fprintf(ficlog," %.12e",p[j]);
                   2643:       }
                   2644:       printf("\n");
                   2645:       fprintf(ficlog,"\n");
                   2646:       for(l=0;l<=1;l++) {
                   2647:        for (j=1;j<=n;j++) {
                   2648:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2649:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2650:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2651:        }
                   2652:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2653:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2654:       }
                   2655: #endif
                   2656: 
                   2657:       free_vector(xit,1,n); 
                   2658:       free_vector(xits,1,n); 
                   2659:       free_vector(ptt,1,n); 
                   2660:       free_vector(pt,1,n); 
                   2661:       return; 
1.192     brouard  2662:     } /* enough precision */ 
1.240     brouard  2663:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2664:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2665:       ptt[j]=2.0*p[j]-pt[j]; 
                   2666:       xit[j]=p[j]-pt[j]; 
                   2667:       pt[j]=p[j]; 
                   2668:     } 
1.181     brouard  2669:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2670: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2671:                if (*iter <=4) {
1.225     brouard  2672: #else
                   2673: #endif
1.224     brouard  2674: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2675: #else
1.161     brouard  2676:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2677: #endif
1.162     brouard  2678:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2679:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2680:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2681:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2682:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2683:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2684:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2685:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2686:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2687:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2688:       /* mu² and del² are equal when f3=f1 */
                   2689:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2690:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2691:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2692:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2693: #ifdef NRCORIGINAL
                   2694:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2695: #else
                   2696:       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  2697:       t= t- del*SQR(fp-fptt);
1.183     brouard  2698: #endif
1.202     brouard  2699:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2700: #ifdef DEBUG
1.181     brouard  2701:       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);
                   2702:       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  2703:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2704:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2705:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2706:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2707:       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);
                   2708:       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);
                   2709: #endif
1.183     brouard  2710: #ifdef POWELLORIGINAL
                   2711:       if (t < 0.0) { /* Then we use it for new direction */
                   2712: #else
1.182     brouard  2713:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2714:                                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  2715:         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  2716:         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  2717:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2718:       } 
1.181     brouard  2719:       if (directest < 0.0) { /* Then we use it for new direction */
                   2720: #endif
1.191     brouard  2721: #ifdef DEBUGLINMIN
1.234     brouard  2722:        printf("Before linmin in direction P%d-P0\n",n);
                   2723:        for (j=1;j<=n;j++) {
                   2724:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2725:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2726:          if(j % ncovmodel == 0){
                   2727:            printf("\n");
                   2728:            fprintf(ficlog,"\n");
                   2729:          }
                   2730:        }
1.224     brouard  2731: #endif
                   2732: #ifdef LINMINORIGINAL
1.234     brouard  2733:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2734: #else
1.234     brouard  2735:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2736:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2737: #endif
1.234     brouard  2738:        
1.191     brouard  2739: #ifdef DEBUGLINMIN
1.234     brouard  2740:        for (j=1;j<=n;j++) { 
                   2741:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2742:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2743:          if(j % ncovmodel == 0){
                   2744:            printf("\n");
                   2745:            fprintf(ficlog,"\n");
                   2746:          }
                   2747:        }
1.224     brouard  2748: #endif
1.234     brouard  2749:        for (j=1;j<=n;j++) { 
                   2750:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2751:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2752:        }
1.224     brouard  2753: #ifdef LINMINORIGINAL
                   2754: #else
1.234     brouard  2755:        for (j=1, flatd=0;j<=n;j++) {
                   2756:          if(flatdir[j]>0)
                   2757:            flatd++;
                   2758:        }
                   2759:        if(flatd >0){
1.255     brouard  2760:          printf("%d flat directions: ",flatd);
                   2761:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2762:          for (j=1;j<=n;j++) { 
                   2763:            if(flatdir[j]>0){
                   2764:              printf("%d ",j);
                   2765:              fprintf(ficlog,"%d ",j);
                   2766:            }
                   2767:          }
                   2768:          printf("\n");
                   2769:          fprintf(ficlog,"\n");
1.319     brouard  2770: #ifdef FLATSUP
                   2771:           free_vector(xit,1,n); 
                   2772:           free_vector(xits,1,n); 
                   2773:           free_vector(ptt,1,n); 
                   2774:           free_vector(pt,1,n); 
                   2775:           return;
                   2776: #endif
1.234     brouard  2777:        }
1.191     brouard  2778: #endif
1.234     brouard  2779:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2780:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2781:        
1.126     brouard  2782: #ifdef DEBUG
1.234     brouard  2783:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2784:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2785:        for(j=1;j<=n;j++){
                   2786:          printf(" %lf",xit[j]);
                   2787:          fprintf(ficlog," %lf",xit[j]);
                   2788:        }
                   2789:        printf("\n");
                   2790:        fprintf(ficlog,"\n");
1.126     brouard  2791: #endif
1.192     brouard  2792:       } /* end of t or directest negative */
1.224     brouard  2793: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2794: #else
1.234     brouard  2795:       } /* end if (fptt < fp)  */
1.192     brouard  2796: #endif
1.225     brouard  2797: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2798:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2799: #else
1.224     brouard  2800: #endif
1.234     brouard  2801:                } /* loop iteration */ 
1.126     brouard  2802: } 
1.234     brouard  2803:   
1.126     brouard  2804: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2805:   
1.235     brouard  2806:   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  2807:   {
1.279     brouard  2808:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2809:      *   (and selected quantitative values in nres)
                   2810:      *  by left multiplying the unit
                   2811:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2812:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2813:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2814:      * or prevalence in state 1, prevalence in state 2, 0
                   2815:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2816:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2817:      * Output is prlim.
                   2818:      * Initial matrix pimij 
                   2819:      */
1.206     brouard  2820:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2821:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2822:   /*  0,                   0                  , 1} */
                   2823:   /*
                   2824:    * and after some iteration: */
                   2825:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2826:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2827:   /*  0,                   0                  , 1} */
                   2828:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2829:   /* {0.51571254859325999, 0.4842874514067399, */
                   2830:   /*  0.51326036147820708, 0.48673963852179264} */
                   2831:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2832:     
1.332     brouard  2833:     int i, ii,j,k, k1;
1.209     brouard  2834:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2835:   /* double **matprod2(); */ /* test */
1.218     brouard  2836:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2837:   double **newm;
1.209     brouard  2838:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2839:   int ncvloop=0;
1.288     brouard  2840:   int first=0;
1.169     brouard  2841:   
1.209     brouard  2842:   min=vector(1,nlstate);
                   2843:   max=vector(1,nlstate);
                   2844:   meandiff=vector(1,nlstate);
                   2845: 
1.218     brouard  2846:        /* Starting with matrix unity */
1.126     brouard  2847:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2848:     for (j=1;j<=nlstate+ndeath;j++){
                   2849:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2850:     }
1.169     brouard  2851:   
                   2852:   cov[1]=1.;
                   2853:   
                   2854:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2855:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2856:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2857:     ncvloop++;
1.126     brouard  2858:     newm=savm;
                   2859:     /* Covariates have to be included here again */
1.138     brouard  2860:     cov[2]=agefin;
1.319     brouard  2861:      if(nagesqr==1){
                   2862:       cov[3]= agefin*agefin;
                   2863:      }
1.332     brouard  2864:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2865:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2866:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2867:        if(Typevar[k1]==1){ /* A product with age */
                   2868:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2869:        }else{
                   2870:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2871:        }
                   2872:      }/* End of loop on model equation */
                   2873:      
                   2874: /* Start of old code (replaced by a loop on position in the model equation */
                   2875:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2876:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2877:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2878:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2879:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2880:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2881:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2882:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2883:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2884:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2885:     /*    *nsd=3                              (1)  (2)           (3) */
                   2886:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2887:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2888:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2889:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2890:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2891:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2892:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2893:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2894:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2895:     /*    *TvarsDpType */
                   2896:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2897:     /*    * nsd=1              (1)           (2) */
                   2898:     /*    *TvarsD[nsd]          3             2 */
                   2899:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2900:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2901:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2902:     /*    *\/ */
                   2903:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2904:     /*   /\* 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)); *\/ */
                   2905:     /* } */
                   2906:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2907:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2908:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2909:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2910:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2911:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2912:     /*   /\* 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]); *\/ */
                   2913:     /* } */
                   2914:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2915:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2916:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2917:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2918:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2919:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2920:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2921:     /*   } */
                   2922:     /*   /\* 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]); *\/ */
                   2923:     /* } */
                   2924:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2925:     /*   /\* 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]); *\/ */
                   2926:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2927:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2928:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2929:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2930:     /*         }else{ */
                   2931:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2932:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2933:     /*         } */
                   2934:     /*   }else{ */
                   2935:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2936:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2937:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2938:     /*         }else{ */
                   2939:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2940:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2941:     /*         } */
                   2942:     /*   } */
                   2943:     /* } /\* End product without age *\/ */
                   2944: /* ENd of old code */
1.138     brouard  2945:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2946:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2947:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2948:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2949:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2950:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2951:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2952:     
1.126     brouard  2953:     savm=oldm;
                   2954:     oldm=newm;
1.209     brouard  2955: 
                   2956:     for(j=1; j<=nlstate; j++){
                   2957:       max[j]=0.;
                   2958:       min[j]=1.;
                   2959:     }
                   2960:     for(i=1;i<=nlstate;i++){
                   2961:       sumnew=0;
                   2962:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2963:       for(j=1; j<=nlstate; j++){ 
                   2964:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2965:        max[j]=FMAX(max[j],prlim[i][j]);
                   2966:        min[j]=FMIN(min[j],prlim[i][j]);
                   2967:       }
                   2968:     }
                   2969: 
1.126     brouard  2970:     maxmax=0.;
1.209     brouard  2971:     for(j=1; j<=nlstate; j++){
                   2972:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2973:       maxmax=FMAX(maxmax,meandiff[j]);
                   2974:       /* 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  2975:     } /* j loop */
1.203     brouard  2976:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2977:     /* 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  2978:     if(maxmax < ftolpl){
1.209     brouard  2979:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2980:       free_vector(min,1,nlstate);
                   2981:       free_vector(max,1,nlstate);
                   2982:       free_vector(meandiff,1,nlstate);
1.126     brouard  2983:       return prlim;
                   2984:     }
1.288     brouard  2985:   } /* agefin loop */
1.208     brouard  2986:     /* After some age loop it doesn't converge */
1.288     brouard  2987:   if(!first){
                   2988:     first=1;
                   2989:     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  2990:     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);
                   2991:   }else if (first >=1 && first <10){
                   2992:     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);
                   2993:     first++;
                   2994:   }else if (first ==10){
                   2995:     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);
                   2996:     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");
                   2997:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   2998:     first++;
1.288     brouard  2999:   }
                   3000: 
1.209     brouard  3001:   /* 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); */
                   3002:   free_vector(min,1,nlstate);
                   3003:   free_vector(max,1,nlstate);
                   3004:   free_vector(meandiff,1,nlstate);
1.208     brouard  3005:   
1.169     brouard  3006:   return prlim; /* should not reach here */
1.126     brouard  3007: }
                   3008: 
1.217     brouard  3009: 
                   3010:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3011: 
1.218     brouard  3012:  /* 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) */
                   3013:  /* 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  3014:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3015: {
1.264     brouard  3016:   /* 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  3017:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3018:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3019:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3020:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3021:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3022:   /* Initial matrix pimij */
                   3023:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3024:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3025:   /*  0,                   0                  , 1} */
                   3026:   /*
                   3027:    * and after some iteration: */
                   3028:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3029:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3030:   /*  0,                   0                  , 1} */
                   3031:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3032:   /* {0.51571254859325999, 0.4842874514067399, */
                   3033:   /*  0.51326036147820708, 0.48673963852179264} */
                   3034:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3035: 
1.332     brouard  3036:   int i, ii,j,k, k1;
1.247     brouard  3037:   int first=0;
1.217     brouard  3038:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3039:   /* double **matprod2(); */ /* test */
                   3040:   double **out, cov[NCOVMAX+1], **bmij();
                   3041:   double **newm;
1.218     brouard  3042:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3043:   double        **oldm, **savm;  /* for use */
                   3044: 
1.217     brouard  3045:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3046:   int ncvloop=0;
                   3047:   
                   3048:   min=vector(1,nlstate);
                   3049:   max=vector(1,nlstate);
                   3050:   meandiff=vector(1,nlstate);
                   3051: 
1.266     brouard  3052:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3053:   oldm=oldms; savm=savms;
                   3054:   
                   3055:   /* Starting with matrix unity */
                   3056:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3057:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3058:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3059:     }
                   3060:   
                   3061:   cov[1]=1.;
                   3062:   
                   3063:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3064:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3065:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3066:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3067:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3068:     ncvloop++;
1.218     brouard  3069:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3070:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3071:     /* Covariates have to be included here again */
                   3072:     cov[2]=agefin;
1.319     brouard  3073:     if(nagesqr==1){
1.217     brouard  3074:       cov[3]= agefin*agefin;;
1.319     brouard  3075:     }
1.332     brouard  3076:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3077:       if(Typevar[k1]==1){ /* A product with age */
                   3078:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3079:       }else{
1.332     brouard  3080:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3081:       }
1.332     brouard  3082:     }/* End of loop on model equation */
                   3083: 
                   3084: /* Old code */ 
                   3085: 
                   3086:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3087:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3088:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3089:     /*   /\* 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)); *\/ */
                   3090:     /* } */
                   3091:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3092:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3093:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3094:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3095:     /* /\* } *\/ */
                   3096:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3097:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3098:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3099:     /*   /\* 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]); *\/ */
                   3100:     /* } */
                   3101:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3102:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3103:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3104:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3105:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3106:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3107:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3108:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3109:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3110:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3111:     /*   } */
                   3112:     /*   /\* 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]); *\/ */
                   3113:     /* } */
                   3114:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3115:     /*   /\* 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]); *\/ */
                   3116:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3117:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3118:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3119:     /*         }else{ */
                   3120:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3121:     /*         } */
                   3122:     /*   }else{ */
                   3123:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3124:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3125:     /*         }else{ */
                   3126:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3127:     /*         } */
                   3128:     /*   } */
                   3129:     /* } */
1.217     brouard  3130:     
                   3131:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3132:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3133:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3134:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3135:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3136:                /* ij should be linked to the correct index of cov */
                   3137:                /* age and covariate values ij are in 'cov', but we need to pass
                   3138:                 * ij for the observed prevalence at age and status and covariate
                   3139:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3140:                 */
                   3141:     /* 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 *\/ */
                   3142:     /* 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 *\/ */
                   3143:     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  3144:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3145:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3146:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3147:     /*         printf("%d newm= ",i); */
                   3148:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3149:     /*           printf("%f ",newm[i][j]); */
                   3150:     /*         } */
                   3151:     /*         printf("oldm * "); */
                   3152:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3153:     /*           printf("%f ",oldm[i][j]); */
                   3154:     /*         } */
1.268     brouard  3155:     /*         printf(" bmmij "); */
1.266     brouard  3156:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3157:     /*           printf("%f ",pmmij[i][j]); */
                   3158:     /*         } */
                   3159:     /*         printf("\n"); */
                   3160:     /*   } */
                   3161:     /* } */
1.217     brouard  3162:     savm=oldm;
                   3163:     oldm=newm;
1.266     brouard  3164: 
1.217     brouard  3165:     for(j=1; j<=nlstate; j++){
                   3166:       max[j]=0.;
                   3167:       min[j]=1.;
                   3168:     }
                   3169:     for(j=1; j<=nlstate; j++){ 
                   3170:       for(i=1;i<=nlstate;i++){
1.234     brouard  3171:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3172:        bprlim[i][j]= newm[i][j];
                   3173:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3174:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3175:       }
                   3176:     }
1.218     brouard  3177:                
1.217     brouard  3178:     maxmax=0.;
                   3179:     for(i=1; i<=nlstate; i++){
1.318     brouard  3180:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3181:       maxmax=FMAX(maxmax,meandiff[i]);
                   3182:       /* 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  3183:     } /* i loop */
1.217     brouard  3184:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3185:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3186:     if(maxmax < ftolpl){
1.220     brouard  3187:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3188:       free_vector(min,1,nlstate);
                   3189:       free_vector(max,1,nlstate);
                   3190:       free_vector(meandiff,1,nlstate);
                   3191:       return bprlim;
                   3192:     }
1.288     brouard  3193:   } /* agefin loop */
1.217     brouard  3194:     /* After some age loop it doesn't converge */
1.288     brouard  3195:   if(!first){
1.247     brouard  3196:     first=1;
                   3197:     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\
                   3198: 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);
                   3199:   }
                   3200:   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  3201: 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);
                   3202:   /* 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); */
                   3203:   free_vector(min,1,nlstate);
                   3204:   free_vector(max,1,nlstate);
                   3205:   free_vector(meandiff,1,nlstate);
                   3206:   
                   3207:   return bprlim; /* should not reach here */
                   3208: }
                   3209: 
1.126     brouard  3210: /*************** transition probabilities ***************/ 
                   3211: 
                   3212: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3213: {
1.138     brouard  3214:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3215:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3216:      model to the ncovmodel covariates (including constant and age).
                   3217:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3218:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3219:      ncth covariate in the global vector x is given by the formula:
                   3220:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3221:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3222:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3223:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3224:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3225:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3226:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3227:   */
                   3228:   double s1, lnpijopii;
1.126     brouard  3229:   /*double t34;*/
1.164     brouard  3230:   int i,j, nc, ii, jj;
1.126     brouard  3231: 
1.223     brouard  3232:   for(i=1; i<= nlstate; i++){
                   3233:     for(j=1; j<i;j++){
                   3234:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3235:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3236:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3237:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3238:       }
                   3239:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3240:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3241:     }
                   3242:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3243:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3244:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3245:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3246:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3247:       }
                   3248:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3249:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3250:     }
                   3251:   }
1.218     brouard  3252:   
1.223     brouard  3253:   for(i=1; i<= nlstate; i++){
                   3254:     s1=0;
                   3255:     for(j=1; j<i; j++){
                   3256:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3257:       /* 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  3258:     }
                   3259:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3260:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3261:       /* 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  3262:     }
                   3263:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3264:     ps[i][i]=1./(s1+1.);
                   3265:     /* Computing other pijs */
                   3266:     for(j=1; j<i; j++)
1.325     brouard  3267:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3268:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3269:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3270:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3271:   } /* end i */
1.218     brouard  3272:   
1.223     brouard  3273:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3274:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3275:       ps[ii][jj]=0;
                   3276:       ps[ii][ii]=1;
                   3277:     }
                   3278:   }
1.294     brouard  3279: 
                   3280: 
1.223     brouard  3281:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3282:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3283:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3284:   /*   } */
                   3285:   /*   printf("\n "); */
                   3286:   /* } */
                   3287:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3288:   /*
                   3289:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3290:                goto end;*/
1.266     brouard  3291:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3292: }
                   3293: 
1.218     brouard  3294: /*************** backward transition probabilities ***************/ 
                   3295: 
                   3296:  /* 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 ) */
                   3297: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3298:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3299: {
1.302     brouard  3300:   /* 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  3301:    * 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  3302:    */
1.218     brouard  3303:   int i, ii, j,k;
1.222     brouard  3304:   
                   3305:   double **out, **pmij();
                   3306:   double sumnew=0.;
1.218     brouard  3307:   double agefin;
1.292     brouard  3308:   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  3309:   double **dnewm, **dsavm, **doldm;
                   3310:   double **bbmij;
                   3311:   
1.218     brouard  3312:   doldm=ddoldms; /* global pointers */
1.222     brouard  3313:   dnewm=ddnewms;
                   3314:   dsavm=ddsavms;
1.318     brouard  3315: 
                   3316:   /* Debug */
                   3317:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3318:   agefin=cov[2];
1.268     brouard  3319:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3320:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3321:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3322:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3323: 
                   3324:   /* P_x */
1.325     brouard  3325:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3326:   /* outputs pmmij which is a stochastic matrix in row */
                   3327: 
                   3328:   /* Diag(w_x) */
1.292     brouard  3329:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3330:   sumnew=0.;
1.269     brouard  3331:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3332:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3333:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3334:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3335:   }
                   3336:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3337:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3338:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3339:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3340:     }
                   3341:   }else{
                   3342:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3343:       for (j=1;j<=nlstate+ndeath;j++)
                   3344:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3345:     }
                   3346:     /* if(sumnew <0.9){ */
                   3347:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3348:     /* } */
                   3349:   }
                   3350:   k3=0.0;  /* We put the last diagonal to 0 */
                   3351:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3352:       doldm[ii][ii]= k3;
                   3353:   }
                   3354:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3355:   
1.292     brouard  3356:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3357:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3358: 
1.292     brouard  3359:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3360:   /* 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  3361:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3362:     sumnew=0.;
1.222     brouard  3363:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3364:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3365:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3366:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3367:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3368:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3369:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3370:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3371:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3372:        /* }else */
1.268     brouard  3373:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3374:     } /*End ii */
                   3375:   } /* 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 */
                   3376: 
1.292     brouard  3377:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3378:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3379:   /* end bmij */
1.266     brouard  3380:   return ps; /*pointer is unchanged */
1.218     brouard  3381: }
1.217     brouard  3382: /*************** transition probabilities ***************/ 
                   3383: 
1.218     brouard  3384: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3385: {
                   3386:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3387:      computes the probability to be observed in state j being in state i by appying the
                   3388:      model to the ncovmodel covariates (including constant and age).
                   3389:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3390:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3391:      ncth covariate in the global vector x is given by the formula:
                   3392:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3393:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3394:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3395:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3396:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3397:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3398:   */
                   3399:   double s1, lnpijopii;
                   3400:   /*double t34;*/
                   3401:   int i,j, nc, ii, jj;
                   3402: 
1.234     brouard  3403:   for(i=1; i<= nlstate; i++){
                   3404:     for(j=1; j<i;j++){
                   3405:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3406:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3407:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3408:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3409:       }
                   3410:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3411:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3412:     }
                   3413:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3414:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3415:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3416:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3417:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3418:       }
                   3419:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3420:     }
                   3421:   }
                   3422:   
                   3423:   for(i=1; i<= nlstate; i++){
                   3424:     s1=0;
                   3425:     for(j=1; j<i; j++){
                   3426:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3427:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3428:     }
                   3429:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3430:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3431:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3432:     }
                   3433:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3434:     ps[i][i]=1./(s1+1.);
                   3435:     /* Computing other pijs */
                   3436:     for(j=1; j<i; j++)
                   3437:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3438:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3439:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3440:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3441:   } /* end i */
                   3442:   
                   3443:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3444:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3445:       ps[ii][jj]=0;
                   3446:       ps[ii][ii]=1;
                   3447:     }
                   3448:   }
1.296     brouard  3449:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3450:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3451:     s1=0.;
                   3452:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3453:       s1+=ps[ii][jj];
                   3454:     }
                   3455:     for(ii=1; ii<= nlstate; ii++){
                   3456:       ps[ii][jj]=ps[ii][jj]/s1;
                   3457:     }
                   3458:   }
                   3459:   /* Transposition */
                   3460:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3461:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3462:       s1=ps[ii][jj];
                   3463:       ps[ii][jj]=ps[jj][ii];
                   3464:       ps[jj][ii]=s1;
                   3465:     }
                   3466:   }
                   3467:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3468:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3469:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3470:   /*   } */
                   3471:   /*   printf("\n "); */
                   3472:   /* } */
                   3473:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3474:   /*
                   3475:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3476:     goto end;*/
                   3477:   return ps;
1.217     brouard  3478: }
                   3479: 
                   3480: 
1.126     brouard  3481: /**************** Product of 2 matrices ******************/
                   3482: 
1.145     brouard  3483: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3484: {
                   3485:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3486:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3487:   /* in, b, out are matrice of pointers which should have been initialized 
                   3488:      before: only the contents of out is modified. The function returns
                   3489:      a pointer to pointers identical to out */
1.145     brouard  3490:   int i, j, k;
1.126     brouard  3491:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3492:     for(k=ncolol; k<=ncoloh; k++){
                   3493:       out[i][k]=0.;
                   3494:       for(j=ncl; j<=nch; j++)
                   3495:        out[i][k] +=in[i][j]*b[j][k];
                   3496:     }
1.126     brouard  3497:   return out;
                   3498: }
                   3499: 
                   3500: 
                   3501: /************* Higher Matrix Product ***************/
                   3502: 
1.235     brouard  3503: 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  3504: {
1.332     brouard  3505:   /* 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  3506:      'nhstepm*hstepm*stepm' months (i.e. until
                   3507:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3508:      nhstepm*hstepm matrices. 
                   3509:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3510:      (typically every 2 years instead of every month which is too big 
                   3511:      for the memory).
                   3512:      Model is determined by parameters x and covariates have to be 
                   3513:      included manually here. 
                   3514: 
                   3515:      */
                   3516: 
1.330     brouard  3517:   int i, j, d, h, k, k1;
1.131     brouard  3518:   double **out, cov[NCOVMAX+1];
1.126     brouard  3519:   double **newm;
1.187     brouard  3520:   double agexact;
1.214     brouard  3521:   double agebegin, ageend;
1.126     brouard  3522: 
                   3523:   /* Hstepm could be zero and should return the unit matrix */
                   3524:   for (i=1;i<=nlstate+ndeath;i++)
                   3525:     for (j=1;j<=nlstate+ndeath;j++){
                   3526:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3527:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3528:     }
                   3529:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3530:   for(h=1; h <=nhstepm; h++){
                   3531:     for(d=1; d <=hstepm; d++){
                   3532:       newm=savm;
                   3533:       /* Covariates have to be included here again */
                   3534:       cov[1]=1.;
1.214     brouard  3535:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3536:       cov[2]=agexact;
1.319     brouard  3537:       if(nagesqr==1){
1.227     brouard  3538:        cov[3]= agexact*agexact;
1.319     brouard  3539:       }
1.330     brouard  3540:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3541:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3542:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3543:        if(Typevar[k1]==1){ /* A product with age */
                   3544:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3545:        }else{
                   3546:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3547:        }
                   3548:       }/* End of loop on model equation */
                   3549:        /* Old code */ 
                   3550: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3551: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3552: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3553: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3554: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3555: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3556: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3557: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3558: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3559: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3560: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3561: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3562: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3563: /*       /\* 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]])); *\/ */
                   3564: /*       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); */
                   3565: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3566: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3567: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3568: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3569: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3570: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3571: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3572: /*       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]]); */
                   3573: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3574: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3575: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3576: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3577: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3578: /*       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]); */
                   3579: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3580: 
                   3581: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3582: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3583: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3584: /*       /\* *\/ */
1.330     brouard  3585: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3586: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3587: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3588: /* /\*cptcovage=2                   1               2      *\/ */
                   3589: /* /\*Tage[k]=                      5               8      *\/  */
                   3590: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3591: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3592: /*       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]]); */
                   3593: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3594: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3595: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3596: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3597: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3598: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3599: /*       /\*   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); *\/ */
                   3600: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3601: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3602: /*       /\* } *\/ */
                   3603: /*       /\* 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]); *\/ */
                   3604: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3605: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3606: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3607: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3608: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3609: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3610: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3611: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3612: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3613:          
1.332     brouard  3614: /*       /\* 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])]); *\/ */
                   3615: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3616: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3617: /*       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]]); */
                   3618: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3619: 
                   3620: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3621: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   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]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3624: /*           /\* 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]])]; *\/ */
                   3625: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3626: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3627: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3628: /*       /\*   } *\/ */
                   3629: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3630: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3631: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3632: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3633: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3634: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3635: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3636: /*       /\*   } *\/ */
                   3637: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3638: /*     }/\*end of products *\/ */
                   3639:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3640:       /* for (k=1; k<=cptcovn;k++)  */
                   3641:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3642:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3643:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3644:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3645:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3646:       
                   3647:       
1.126     brouard  3648:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3649:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3650:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3651:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3652:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3653:       /* if((int)age == 70){ */
                   3654:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3655:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3656:       /*         printf("%d pmmij ",i); */
                   3657:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3658:       /*           printf("%f ",pmmij[i][j]); */
                   3659:       /*         } */
                   3660:       /*         printf(" oldm "); */
                   3661:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3662:       /*           printf("%f ",oldm[i][j]); */
                   3663:       /*         } */
                   3664:       /*         printf("\n"); */
                   3665:       /*       } */
                   3666:       /* } */
1.126     brouard  3667:       savm=oldm;
                   3668:       oldm=newm;
                   3669:     }
                   3670:     for(i=1; i<=nlstate+ndeath; i++)
                   3671:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3672:        po[i][j][h]=newm[i][j];
                   3673:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3674:       }
1.128     brouard  3675:     /*printf("h=%d ",h);*/
1.126     brouard  3676:   } /* end h */
1.267     brouard  3677:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3678:   return po;
                   3679: }
                   3680: 
1.217     brouard  3681: /************* Higher Back Matrix Product ***************/
1.218     brouard  3682: /* 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  3683: 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  3684: {
1.332     brouard  3685:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3686:      computes the transition matrix starting at age 'age' over
1.217     brouard  3687:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3688:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3689:      nhstepm*hstepm matrices.
                   3690:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3691:      (typically every 2 years instead of every month which is too big
1.217     brouard  3692:      for the memory).
1.218     brouard  3693:      Model is determined by parameters x and covariates have to be
1.266     brouard  3694:      included manually here. Then we use a call to bmij(x and cov)
                   3695:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3696:   */
1.217     brouard  3697: 
1.332     brouard  3698:   int i, j, d, h, k, k1;
1.266     brouard  3699:   double **out, cov[NCOVMAX+1], **bmij();
                   3700:   double **newm, ***newmm;
1.217     brouard  3701:   double agexact;
                   3702:   double agebegin, ageend;
1.222     brouard  3703:   double **oldm, **savm;
1.217     brouard  3704: 
1.266     brouard  3705:   newmm=po; /* To be saved */
                   3706:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3707:   /* Hstepm could be zero and should return the unit matrix */
                   3708:   for (i=1;i<=nlstate+ndeath;i++)
                   3709:     for (j=1;j<=nlstate+ndeath;j++){
                   3710:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3711:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3712:     }
                   3713:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3714:   for(h=1; h <=nhstepm; h++){
                   3715:     for(d=1; d <=hstepm; d++){
                   3716:       newm=savm;
                   3717:       /* Covariates have to be included here again */
                   3718:       cov[1]=1.;
1.271     brouard  3719:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3720:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3721:         /* Debug */
                   3722:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3723:       cov[2]=agexact;
1.332     brouard  3724:       if(nagesqr==1){
1.222     brouard  3725:        cov[3]= agexact*agexact;
1.332     brouard  3726:       }
                   3727:       /** New code */
                   3728:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3729:        if(Typevar[k1]==1){ /* A product with age */
                   3730:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3731:        }else{
1.332     brouard  3732:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3733:        }
1.332     brouard  3734:       }/* End of loop on model equation */
                   3735:       /** End of new code */
                   3736:   /** This was old code */
                   3737:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3738:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3739:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3740:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3741:       /*   /\* 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)); *\/ */
                   3742:       /* } */
                   3743:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3744:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3745:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3746:       /*       /\* 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]); *\/ */
                   3747:       /* } */
                   3748:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3749:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3750:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3751:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3752:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3753:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3754:       /*       } */
                   3755:       /*       /\* 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]); *\/ */
                   3756:       /* } */
                   3757:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3758:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3759:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3760:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3761:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3762:       /*         }else{ */
                   3763:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3764:       /*         } */
                   3765:       /*       }else{ */
                   3766:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3767:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3768:       /*         }else{ */
                   3769:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3770:       /*         } */
                   3771:       /*       } */
                   3772:       /* }                      */
                   3773:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3774:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3775: /** End of old code */
                   3776:       
1.218     brouard  3777:       /* Careful transposed matrix */
1.266     brouard  3778:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3779:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3780:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3781:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3782:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3783:       /* if((int)age == 70){ */
                   3784:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3785:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3786:       /*         printf("%d pmmij ",i); */
                   3787:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3788:       /*           printf("%f ",pmmij[i][j]); */
                   3789:       /*         } */
                   3790:       /*         printf(" oldm "); */
                   3791:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3792:       /*           printf("%f ",oldm[i][j]); */
                   3793:       /*         } */
                   3794:       /*         printf("\n"); */
                   3795:       /*       } */
                   3796:       /* } */
                   3797:       savm=oldm;
                   3798:       oldm=newm;
                   3799:     }
                   3800:     for(i=1; i<=nlstate+ndeath; i++)
                   3801:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3802:        po[i][j][h]=newm[i][j];
1.268     brouard  3803:        /* if(h==nhstepm) */
                   3804:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3805:       }
1.268     brouard  3806:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3807:   } /* end h */
1.268     brouard  3808:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3809:   return po;
                   3810: }
                   3811: 
                   3812: 
1.162     brouard  3813: #ifdef NLOPT
                   3814:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3815:   double fret;
                   3816:   double *xt;
                   3817:   int j;
                   3818:   myfunc_data *d2 = (myfunc_data *) pd;
                   3819: /* xt = (p1-1); */
                   3820:   xt=vector(1,n); 
                   3821:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3822: 
                   3823:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3824:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3825:   printf("Function = %.12lf ",fret);
                   3826:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3827:   printf("\n");
                   3828:  free_vector(xt,1,n);
                   3829:   return fret;
                   3830: }
                   3831: #endif
1.126     brouard  3832: 
                   3833: /*************** log-likelihood *************/
                   3834: double func( double *x)
                   3835: {
1.226     brouard  3836:   int i, ii, j, k, mi, d, kk;
                   3837:   int ioffset=0;
                   3838:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3839:   double **out;
                   3840:   double lli; /* Individual log likelihood */
                   3841:   int s1, s2;
1.228     brouard  3842:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.226     brouard  3843:   double bbh, survp;
                   3844:   long ipmx;
                   3845:   double agexact;
                   3846:   /*extern weight */
                   3847:   /* We are differentiating ll according to initial status */
                   3848:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3849:   /*for(i=1;i<imx;i++) 
                   3850:     printf(" %d\n",s[4][i]);
                   3851:   */
1.162     brouard  3852: 
1.226     brouard  3853:   ++countcallfunc;
1.162     brouard  3854: 
1.226     brouard  3855:   cov[1]=1.;
1.126     brouard  3856: 
1.226     brouard  3857:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3858:   ioffset=0;
1.226     brouard  3859:   if(mle==1){
                   3860:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3861:       /* Computes the values of the ncovmodel covariates of the model
                   3862:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3863:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3864:         to be observed in j being in i according to the model.
                   3865:       */
1.243     brouard  3866:       ioffset=2+nagesqr ;
1.233     brouard  3867:    /* Fixed */
1.319     brouard  3868:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3869:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3870:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3871:        /*  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  3872:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3873:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
                   3874:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3875:       }
1.226     brouard  3876:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3877:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3878:         has been calculated etc */
                   3879:       /* For an individual i, wav[i] gives the number of effective waves */
                   3880:       /* We compute the contribution to Likelihood of each effective transition
                   3881:         mw[mi][i] is real wave of the mi th effectve wave */
                   3882:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3883:         s2=s[mw[mi+1][i]][i];
                   3884:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3885:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3886:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3887:       */
                   3888:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3889:        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*/
                   3890:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3891:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3892:        }
                   3893:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3894:          for (j=1;j<=nlstate+ndeath;j++){
                   3895:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3896:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3897:          }
                   3898:        for(d=0; d<dh[mi][i]; d++){
                   3899:          newm=savm;
                   3900:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3901:          cov[2]=agexact;
                   3902:          if(nagesqr==1)
                   3903:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3904:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3905:            if(!FixedV[Tvar[Tage[kk]]])
                   3906:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3907:            else
                   3908:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3909:          }
                   3910:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3911:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3912:          savm=oldm;
                   3913:          oldm=newm;
                   3914:        } /* end mult */
                   3915:        
                   3916:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3917:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3918:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3919:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3920:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3921:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3922:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3923:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3924:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3925:                                 * -stepm/2 to stepm/2 .
                   3926:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3927:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3928:                                 */
1.234     brouard  3929:        s1=s[mw[mi][i]][i];
                   3930:        s2=s[mw[mi+1][i]][i];
                   3931:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3932:        /* bias bh is positive if real duration
                   3933:         * is higher than the multiple of stepm and negative otherwise.
                   3934:         */
                   3935:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3936:        if( s2 > nlstate){ 
                   3937:          /* i.e. if s2 is a death state and if the date of death is known 
                   3938:             then the contribution to the likelihood is the probability to 
                   3939:             die between last step unit time and current  step unit time, 
                   3940:             which is also equal to probability to die before dh 
                   3941:             minus probability to die before dh-stepm . 
                   3942:             In version up to 0.92 likelihood was computed
                   3943:             as if date of death was unknown. Death was treated as any other
                   3944:             health state: the date of the interview describes the actual state
                   3945:             and not the date of a change in health state. The former idea was
                   3946:             to consider that at each interview the state was recorded
                   3947:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3948:             introduced the exact date of death then we should have modified
                   3949:             the contribution of an exact death to the likelihood. This new
                   3950:             contribution is smaller and very dependent of the step unit
                   3951:             stepm. It is no more the probability to die between last interview
                   3952:             and month of death but the probability to survive from last
                   3953:             interview up to one month before death multiplied by the
                   3954:             probability to die within a month. Thanks to Chris
                   3955:             Jackson for correcting this bug.  Former versions increased
                   3956:             mortality artificially. The bad side is that we add another loop
                   3957:             which slows down the processing. The difference can be up to 10%
                   3958:             lower mortality.
                   3959:          */
                   3960:          /* If, at the beginning of the maximization mostly, the
                   3961:             cumulative probability or probability to be dead is
                   3962:             constant (ie = 1) over time d, the difference is equal to
                   3963:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3964:             s1 at precedent wave, to be dead a month before current
                   3965:             wave is equal to probability, being at state s1 at
                   3966:             precedent wave, to be dead at mont of the current
                   3967:             wave. Then the observed probability (that this person died)
                   3968:             is null according to current estimated parameter. In fact,
                   3969:             it should be very low but not zero otherwise the log go to
                   3970:             infinity.
                   3971:          */
1.183     brouard  3972: /* #ifdef INFINITYORIGINAL */
                   3973: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3974: /* #else */
                   3975: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3976: /*         lli=log(mytinydouble); */
                   3977: /*       else */
                   3978: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3979: /* #endif */
1.226     brouard  3980:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3981:          
1.226     brouard  3982:        } else if  ( s2==-1 ) { /* alive */
                   3983:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3984:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3985:          /*survp += out[s1][j]; */
                   3986:          lli= log(survp);
                   3987:        }
                   3988:        else if  (s2==-4) { 
                   3989:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3990:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3991:          lli= log(survp); 
                   3992:        } 
                   3993:        else if  (s2==-5) { 
                   3994:          for (j=1,survp=0. ; j<=2; j++)  
                   3995:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3996:          lli= log(survp); 
                   3997:        } 
                   3998:        else{
                   3999:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4000:          /*  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 */
                   4001:        } 
                   4002:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4003:        /*if(lli ==000.0)*/
                   4004:        /*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); */
                   4005:        ipmx +=1;
                   4006:        sw += weight[i];
                   4007:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4008:        /* if (lli < log(mytinydouble)){ */
                   4009:        /*   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); */
                   4010:        /*   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]); */
                   4011:        /* } */
                   4012:       } /* end of wave */
                   4013:     } /* end of individual */
                   4014:   }  else if(mle==2){
                   4015:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4016:       ioffset=2+nagesqr ;
                   4017:       for (k=1; k<=ncovf;k++)
                   4018:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4019:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4020:        for(k=1; k <= ncovv ; k++){
                   4021:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4022:        }
1.226     brouard  4023:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4024:          for (j=1;j<=nlstate+ndeath;j++){
                   4025:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4026:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4027:          }
                   4028:        for(d=0; d<=dh[mi][i]; d++){
                   4029:          newm=savm;
                   4030:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4031:          cov[2]=agexact;
                   4032:          if(nagesqr==1)
                   4033:            cov[3]= agexact*agexact;
                   4034:          for (kk=1; kk<=cptcovage;kk++) {
                   4035:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4036:          }
                   4037:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4038:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4039:          savm=oldm;
                   4040:          oldm=newm;
                   4041:        } /* end mult */
                   4042:       
                   4043:        s1=s[mw[mi][i]][i];
                   4044:        s2=s[mw[mi+1][i]][i];
                   4045:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4046:        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 */
                   4047:        ipmx +=1;
                   4048:        sw += weight[i];
                   4049:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4050:       } /* end of wave */
                   4051:     } /* end of individual */
                   4052:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4053:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4054:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4055:       for(mi=1; mi<= wav[i]-1; mi++){
                   4056:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4057:          for (j=1;j<=nlstate+ndeath;j++){
                   4058:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4059:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4060:          }
                   4061:        for(d=0; d<dh[mi][i]; d++){
                   4062:          newm=savm;
                   4063:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4064:          cov[2]=agexact;
                   4065:          if(nagesqr==1)
                   4066:            cov[3]= agexact*agexact;
                   4067:          for (kk=1; kk<=cptcovage;kk++) {
                   4068:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4069:          }
                   4070:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4071:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4072:          savm=oldm;
                   4073:          oldm=newm;
                   4074:        } /* end mult */
                   4075:       
                   4076:        s1=s[mw[mi][i]][i];
                   4077:        s2=s[mw[mi+1][i]][i];
                   4078:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4079:        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 */
                   4080:        ipmx +=1;
                   4081:        sw += weight[i];
                   4082:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4083:       } /* end of wave */
                   4084:     } /* end of individual */
                   4085:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4086:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4087:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4088:       for(mi=1; mi<= wav[i]-1; mi++){
                   4089:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4090:          for (j=1;j<=nlstate+ndeath;j++){
                   4091:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4092:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4093:          }
                   4094:        for(d=0; d<dh[mi][i]; d++){
                   4095:          newm=savm;
                   4096:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4097:          cov[2]=agexact;
                   4098:          if(nagesqr==1)
                   4099:            cov[3]= agexact*agexact;
                   4100:          for (kk=1; kk<=cptcovage;kk++) {
                   4101:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4102:          }
1.126     brouard  4103:        
1.226     brouard  4104:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4105:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4106:          savm=oldm;
                   4107:          oldm=newm;
                   4108:        } /* end mult */
                   4109:       
                   4110:        s1=s[mw[mi][i]][i];
                   4111:        s2=s[mw[mi+1][i]][i];
                   4112:        if( s2 > nlstate){ 
                   4113:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4114:        } else if  ( s2==-1 ) { /* alive */
                   4115:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4116:            survp += out[s1][j];
                   4117:          lli= log(survp);
                   4118:        }else{
                   4119:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4120:        }
                   4121:        ipmx +=1;
                   4122:        sw += weight[i];
                   4123:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4124: /*     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  4125:       } /* end of wave */
                   4126:     } /* end of individual */
                   4127:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4128:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4129:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4130:       for(mi=1; mi<= wav[i]-1; mi++){
                   4131:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4132:          for (j=1;j<=nlstate+ndeath;j++){
                   4133:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4134:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4135:          }
                   4136:        for(d=0; d<dh[mi][i]; d++){
                   4137:          newm=savm;
                   4138:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4139:          cov[2]=agexact;
                   4140:          if(nagesqr==1)
                   4141:            cov[3]= agexact*agexact;
                   4142:          for (kk=1; kk<=cptcovage;kk++) {
                   4143:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4144:          }
1.126     brouard  4145:        
1.226     brouard  4146:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4147:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4148:          savm=oldm;
                   4149:          oldm=newm;
                   4150:        } /* end mult */
                   4151:       
                   4152:        s1=s[mw[mi][i]][i];
                   4153:        s2=s[mw[mi+1][i]][i];
                   4154:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4155:        ipmx +=1;
                   4156:        sw += weight[i];
                   4157:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4158:        /*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]);*/
                   4159:       } /* end of wave */
                   4160:     } /* end of individual */
                   4161:   } /* End of if */
                   4162:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4163:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4164:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4165:   return -l;
1.126     brouard  4166: }
                   4167: 
                   4168: /*************** log-likelihood *************/
                   4169: double funcone( double *x)
                   4170: {
1.228     brouard  4171:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  4172:   int i, ii, j, k, mi, d, kk;
1.228     brouard  4173:   int ioffset=0;
1.131     brouard  4174:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4175:   double **out;
                   4176:   double lli; /* Individual log likelihood */
                   4177:   double llt;
                   4178:   int s1, s2;
1.228     brouard  4179:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4180: 
1.126     brouard  4181:   double bbh, survp;
1.187     brouard  4182:   double agexact;
1.214     brouard  4183:   double agebegin, ageend;
1.126     brouard  4184:   /*extern weight */
                   4185:   /* We are differentiating ll according to initial status */
                   4186:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4187:   /*for(i=1;i<imx;i++) 
                   4188:     printf(" %d\n",s[4][i]);
                   4189:   */
                   4190:   cov[1]=1.;
                   4191: 
                   4192:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4193:   ioffset=0;
                   4194:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4195:     /* ioffset=2+nagesqr+cptcovage; */
                   4196:     ioffset=2+nagesqr;
1.232     brouard  4197:     /* Fixed */
1.224     brouard  4198:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4199:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.311     brouard  4200:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.232     brouard  4201:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   4202: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4203: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4204: /*    cov[2+6]=covar[2][i]; V2  */
                   4205: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4206: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4207: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4208: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4209: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4210: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4211:     }
1.232     brouard  4212:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4213:     /*   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?)*\/ */
                   4214:     /* } */
1.231     brouard  4215:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4216:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4217:     /* } */
1.225     brouard  4218:     
1.233     brouard  4219: 
                   4220:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4221:     /* Wave varying (but not age varying) */
                   4222:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4223:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4224:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4225:       }
1.232     brouard  4226:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4227:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4228:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4229:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4230:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4231:       /* 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  4232:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4233:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4234:       /*       /\* 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]); *\/ */
                   4235:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4236:       /* } */
1.126     brouard  4237:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4238:        for (j=1;j<=nlstate+ndeath;j++){
                   4239:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4240:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4241:        }
1.214     brouard  4242:       
                   4243:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4244:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4245:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4246:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4247:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4248:          and mw[mi+1][i]. dh depends on stepm.*/
                   4249:        newm=savm;
1.247     brouard  4250:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4251:        cov[2]=agexact;
                   4252:        if(nagesqr==1)
                   4253:          cov[3]= agexact*agexact;
                   4254:        for (kk=1; kk<=cptcovage;kk++) {
                   4255:          if(!FixedV[Tvar[Tage[kk]]])
                   4256:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4257:          else
                   4258:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4259:        }
                   4260:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4261:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4262:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4263:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4264:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4265:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4266:        savm=oldm;
                   4267:        oldm=newm;
1.126     brouard  4268:       } /* end mult */
                   4269:       
                   4270:       s1=s[mw[mi][i]][i];
                   4271:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4272:       /* if(s2==-1){ */
1.268     brouard  4273:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4274:       /*       /\* exit(1); *\/ */
                   4275:       /* } */
1.126     brouard  4276:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4277:       /* bias is positive if real duration
                   4278:        * is higher than the multiple of stepm and negative otherwise.
                   4279:        */
                   4280:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4281:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4282:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4283:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4284:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4285:        lli= log(survp);
1.126     brouard  4286:       }else if (mle==1){
1.242     brouard  4287:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4288:       } else if(mle==2){
1.242     brouard  4289:        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  4290:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4291:        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  4292:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4293:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4294:       } else{  /* mle=0 back to 1 */
1.242     brouard  4295:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4296:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4297:       } /* End of if */
                   4298:       ipmx +=1;
                   4299:       sw += weight[i];
                   4300:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  4301:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  4302:       if(globpr){
1.246     brouard  4303:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4304:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4305:                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  4306:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.242     brouard  4307:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4308:          llt +=ll[k]*gipmx/gsw;
                   4309:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4310:        }
                   4311:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  4312:       }
1.232     brouard  4313:        } /* end of wave */
                   4314: } /* end of individual */
                   4315: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4316: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4317: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4318: if(globpr==0){ /* First time we count the contributions and weights */
                   4319:        gipmx=ipmx;
                   4320:        gsw=sw;
                   4321: }
                   4322: return -l;
1.126     brouard  4323: }
                   4324: 
                   4325: 
                   4326: /*************** function likelione ***********/
1.292     brouard  4327: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4328: {
                   4329:   /* This routine should help understanding what is done with 
                   4330:      the selection of individuals/waves and
                   4331:      to check the exact contribution to the likelihood.
                   4332:      Plotting could be done.
                   4333:    */
                   4334:   int k;
                   4335: 
                   4336:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4337:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4338:     strcat(fileresilk,fileresu);
1.126     brouard  4339:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4340:       printf("Problem with resultfile: %s\n", fileresilk);
                   4341:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4342:     }
1.214     brouard  4343:     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");
                   4344:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4345:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4346:     for(k=1; k<=nlstate; k++) 
                   4347:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4348:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4349:   }
                   4350: 
1.292     brouard  4351:   *fretone=(*func)(p);
1.126     brouard  4352:   if(*globpri !=0){
                   4353:     fclose(ficresilk);
1.205     brouard  4354:     if (mle ==0)
                   4355:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4356:     else if(mle >=1)
                   4357:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4358:     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  4359:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4360:       
                   4361:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4362:       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  4363: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4364:     }
1.207     brouard  4365:     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  4366: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4367:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4368: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4369:     fflush(fichtm);
1.205     brouard  4370:   }
1.126     brouard  4371:   return;
                   4372: }
                   4373: 
                   4374: 
                   4375: /*********** Maximum Likelihood Estimation ***************/
                   4376: 
                   4377: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4378: {
1.319     brouard  4379:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4380:   double **xi;
                   4381:   double fret;
                   4382:   double fretone; /* Only one call to likelihood */
                   4383:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4384: 
                   4385: #ifdef NLOPT
                   4386:   int creturn;
                   4387:   nlopt_opt opt;
                   4388:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4389:   double *lb;
                   4390:   double minf; /* the minimum objective value, upon return */
                   4391:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4392:   myfunc_data dinst, *d = &dinst;
                   4393: #endif
                   4394: 
                   4395: 
1.126     brouard  4396:   xi=matrix(1,npar,1,npar);
                   4397:   for (i=1;i<=npar;i++)
                   4398:     for (j=1;j<=npar;j++)
                   4399:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4400:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4401:   strcpy(filerespow,"POW_"); 
1.126     brouard  4402:   strcat(filerespow,fileres);
                   4403:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4404:     printf("Problem with resultfile: %s\n", filerespow);
                   4405:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4406:   }
                   4407:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4408:   for (i=1;i<=nlstate;i++)
                   4409:     for(j=1;j<=nlstate+ndeath;j++)
                   4410:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4411:   fprintf(ficrespow,"\n");
1.162     brouard  4412: #ifdef POWELL
1.319     brouard  4413: #ifdef LINMINORIGINAL
                   4414: #else /* LINMINORIGINAL */
                   4415:   
                   4416:   flatdir=ivector(1,npar); 
                   4417:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4418: #endif /*LINMINORIGINAL */
                   4419: 
                   4420: #ifdef FLATSUP
                   4421:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4422:   /* reorganizing p by suppressing flat directions */
                   4423:   for(i=1, jk=1; i <=nlstate; i++){
                   4424:     for(k=1; k <=(nlstate+ndeath); k++){
                   4425:       if (k != i) {
                   4426:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4427:         if(flatdir[jk]==1){
                   4428:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4429:         }
                   4430:         for(j=1; j <=ncovmodel; j++){
                   4431:           printf("%12.7f ",p[jk]);
                   4432:           jk++; 
                   4433:         }
                   4434:         printf("\n");
                   4435:       }
                   4436:     }
                   4437:   }
                   4438: /* skipping */
                   4439:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4440:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4441:     for(k=1; k <=(nlstate+ndeath); k++){
                   4442:       if (k != i) {
                   4443:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4444:         if(flatdir[jk]==1){
                   4445:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4446:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4447:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4448:             /*q[jjk]=p[jk];*/
                   4449:           }
                   4450:         }else{
                   4451:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4452:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4453:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4454:             /*q[jjk]=p[jk];*/
                   4455:           }
                   4456:         }
                   4457:         printf("\n");
                   4458:       }
                   4459:       fflush(stdout);
                   4460:     }
                   4461:   }
                   4462:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4463: #else  /* FLATSUP */
1.126     brouard  4464:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4465: #endif  /* FLATSUP */
                   4466: 
                   4467: #ifdef LINMINORIGINAL
                   4468: #else
                   4469:       free_ivector(flatdir,1,npar); 
                   4470: #endif  /* LINMINORIGINAL*/
                   4471: #endif /* POWELL */
1.126     brouard  4472: 
1.162     brouard  4473: #ifdef NLOPT
                   4474: #ifdef NEWUOA
                   4475:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4476: #else
                   4477:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4478: #endif
                   4479:   lb=vector(0,npar-1);
                   4480:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4481:   nlopt_set_lower_bounds(opt, lb);
                   4482:   nlopt_set_initial_step1(opt, 0.1);
                   4483:   
                   4484:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4485:   d->function = func;
                   4486:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4487:   nlopt_set_min_objective(opt, myfunc, d);
                   4488:   nlopt_set_xtol_rel(opt, ftol);
                   4489:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4490:     printf("nlopt failed! %d\n",creturn); 
                   4491:   }
                   4492:   else {
                   4493:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4494:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4495:     iter=1; /* not equal */
                   4496:   }
                   4497:   nlopt_destroy(opt);
                   4498: #endif
1.319     brouard  4499: #ifdef FLATSUP
                   4500:   /* npared = npar -flatd/ncovmodel; */
                   4501:   /* xired= matrix(1,npared,1,npared); */
                   4502:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4503:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4504:   /* free_matrix(xire,1,npared,1,npared); */
                   4505: #else  /* FLATSUP */
                   4506: #endif /* FLATSUP */
1.126     brouard  4507:   free_matrix(xi,1,npar,1,npar);
                   4508:   fclose(ficrespow);
1.203     brouard  4509:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4510:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4511:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4512: 
                   4513: }
                   4514: 
                   4515: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4516: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4517: {
                   4518:   double  **a,**y,*x,pd;
1.203     brouard  4519:   /* double **hess; */
1.164     brouard  4520:   int i, j;
1.126     brouard  4521:   int *indx;
                   4522: 
                   4523:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4524:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4525:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4526:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4527:   double gompertz(double p[]);
1.203     brouard  4528:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4529: 
                   4530:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4531:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4532:   for (i=1;i<=npar;i++){
1.203     brouard  4533:     printf("%d-",i);fflush(stdout);
                   4534:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4535:    
                   4536:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4537:     
                   4538:     /*  printf(" %f ",p[i]);
                   4539:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4540:   }
                   4541:   
                   4542:   for (i=1;i<=npar;i++) {
                   4543:     for (j=1;j<=npar;j++)  {
                   4544:       if (j>i) { 
1.203     brouard  4545:        printf(".%d-%d",i,j);fflush(stdout);
                   4546:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4547:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4548:        
                   4549:        hess[j][i]=hess[i][j];    
                   4550:        /*printf(" %lf ",hess[i][j]);*/
                   4551:       }
                   4552:     }
                   4553:   }
                   4554:   printf("\n");
                   4555:   fprintf(ficlog,"\n");
                   4556: 
                   4557:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4558:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4559:   
                   4560:   a=matrix(1,npar,1,npar);
                   4561:   y=matrix(1,npar,1,npar);
                   4562:   x=vector(1,npar);
                   4563:   indx=ivector(1,npar);
                   4564:   for (i=1;i<=npar;i++)
                   4565:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4566:   ludcmp(a,npar,indx,&pd);
                   4567: 
                   4568:   for (j=1;j<=npar;j++) {
                   4569:     for (i=1;i<=npar;i++) x[i]=0;
                   4570:     x[j]=1;
                   4571:     lubksb(a,npar,indx,x);
                   4572:     for (i=1;i<=npar;i++){ 
                   4573:       matcov[i][j]=x[i];
                   4574:     }
                   4575:   }
                   4576: 
                   4577:   printf("\n#Hessian matrix#\n");
                   4578:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4579:   for (i=1;i<=npar;i++) { 
                   4580:     for (j=1;j<=npar;j++) { 
1.203     brouard  4581:       printf("%.6e ",hess[i][j]);
                   4582:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4583:     }
                   4584:     printf("\n");
                   4585:     fprintf(ficlog,"\n");
                   4586:   }
                   4587: 
1.203     brouard  4588:   /* printf("\n#Covariance matrix#\n"); */
                   4589:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4590:   /* for (i=1;i<=npar;i++) {  */
                   4591:   /*   for (j=1;j<=npar;j++) {  */
                   4592:   /*     printf("%.6e ",matcov[i][j]); */
                   4593:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4594:   /*   } */
                   4595:   /*   printf("\n"); */
                   4596:   /*   fprintf(ficlog,"\n"); */
                   4597:   /* } */
                   4598: 
1.126     brouard  4599:   /* Recompute Inverse */
1.203     brouard  4600:   /* for (i=1;i<=npar;i++) */
                   4601:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4602:   /* ludcmp(a,npar,indx,&pd); */
                   4603: 
                   4604:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4605: 
                   4606:   /* for (j=1;j<=npar;j++) { */
                   4607:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4608:   /*   x[j]=1; */
                   4609:   /*   lubksb(a,npar,indx,x); */
                   4610:   /*   for (i=1;i<=npar;i++){  */
                   4611:   /*     y[i][j]=x[i]; */
                   4612:   /*     printf("%.3e ",y[i][j]); */
                   4613:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4614:   /*   } */
                   4615:   /*   printf("\n"); */
                   4616:   /*   fprintf(ficlog,"\n"); */
                   4617:   /* } */
                   4618: 
                   4619:   /* Verifying the inverse matrix */
                   4620: #ifdef DEBUGHESS
                   4621:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4622: 
1.203     brouard  4623:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4624:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4625: 
                   4626:   for (j=1;j<=npar;j++) {
                   4627:     for (i=1;i<=npar;i++){ 
1.203     brouard  4628:       printf("%.2f ",y[i][j]);
                   4629:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4630:     }
                   4631:     printf("\n");
                   4632:     fprintf(ficlog,"\n");
                   4633:   }
1.203     brouard  4634: #endif
1.126     brouard  4635: 
                   4636:   free_matrix(a,1,npar,1,npar);
                   4637:   free_matrix(y,1,npar,1,npar);
                   4638:   free_vector(x,1,npar);
                   4639:   free_ivector(indx,1,npar);
1.203     brouard  4640:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4641: 
                   4642: 
                   4643: }
                   4644: 
                   4645: /*************** hessian matrix ****************/
                   4646: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4647: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4648:   int i;
                   4649:   int l=1, lmax=20;
1.203     brouard  4650:   double k1,k2, res, fx;
1.132     brouard  4651:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4652:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4653:   int k=0,kmax=10;
                   4654:   double l1;
                   4655: 
                   4656:   fx=func(x);
                   4657:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4658:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4659:     l1=pow(10,l);
                   4660:     delts=delt;
                   4661:     for(k=1 ; k <kmax; k=k+1){
                   4662:       delt = delta*(l1*k);
                   4663:       p2[theta]=x[theta] +delt;
1.145     brouard  4664:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4665:       p2[theta]=x[theta]-delt;
                   4666:       k2=func(p2)-fx;
                   4667:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4668:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4669:       
1.203     brouard  4670: #ifdef DEBUGHESSII
1.126     brouard  4671:       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);
                   4672:       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);
                   4673: #endif
                   4674:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4675:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4676:        k=kmax;
                   4677:       }
                   4678:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4679:        k=kmax; l=lmax*10;
1.126     brouard  4680:       }
                   4681:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4682:        delts=delt;
                   4683:       }
1.203     brouard  4684:     } /* End loop k */
1.126     brouard  4685:   }
                   4686:   delti[theta]=delts;
                   4687:   return res; 
                   4688:   
                   4689: }
                   4690: 
1.203     brouard  4691: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4692: {
                   4693:   int i;
1.164     brouard  4694:   int l=1, lmax=20;
1.126     brouard  4695:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4696:   double p2[MAXPARM+1];
1.203     brouard  4697:   int k, kmax=1;
                   4698:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4699: 
                   4700:   int firstime=0;
1.203     brouard  4701:   
1.126     brouard  4702:   fx=func(x);
1.203     brouard  4703:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4704:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4705:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4706:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4707:     k1=func(p2)-fx;
                   4708:   
1.203     brouard  4709:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4710:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4711:     k2=func(p2)-fx;
                   4712:   
1.203     brouard  4713:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4714:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4715:     k3=func(p2)-fx;
                   4716:   
1.203     brouard  4717:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4718:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4719:     k4=func(p2)-fx;
1.203     brouard  4720:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4721:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4722:       firstime=1;
1.203     brouard  4723:       kmax=kmax+10;
1.208     brouard  4724:     }
                   4725:     if(kmax >=10 || firstime ==1){
1.246     brouard  4726:       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);
                   4727:       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  4728:       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);
                   4729:       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);
                   4730:     }
                   4731: #ifdef DEBUGHESSIJ
                   4732:     v1=hess[thetai][thetai];
                   4733:     v2=hess[thetaj][thetaj];
                   4734:     cv12=res;
                   4735:     /* Computing eigen value of Hessian matrix */
                   4736:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4737:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4738:     if ((lc2 <0) || (lc1 <0) ){
                   4739:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4740:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4741:       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);
                   4742:       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);
                   4743:     }
1.126     brouard  4744: #endif
                   4745:   }
                   4746:   return res;
                   4747: }
                   4748: 
1.203     brouard  4749:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4750: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4751: /* { */
                   4752: /*   int i; */
                   4753: /*   int l=1, lmax=20; */
                   4754: /*   double k1,k2,k3,k4,res,fx; */
                   4755: /*   double p2[MAXPARM+1]; */
                   4756: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4757: /*   int k=0,kmax=10; */
                   4758: /*   double l1; */
                   4759:   
                   4760: /*   fx=func(x); */
                   4761: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4762: /*     l1=pow(10,l); */
                   4763: /*     delts=delt; */
                   4764: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4765: /*       delt = delti*(l1*k); */
                   4766: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4767: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4768: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4769: /*       k1=func(p2)-fx; */
                   4770:       
                   4771: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4772: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4773: /*       k2=func(p2)-fx; */
                   4774:       
                   4775: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4776: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4777: /*       k3=func(p2)-fx; */
                   4778:       
                   4779: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4780: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4781: /*       k4=func(p2)-fx; */
                   4782: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4783: /* #ifdef DEBUGHESSIJ */
                   4784: /*       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); */
                   4785: /*       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); */
                   4786: /* #endif */
                   4787: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4788: /*     k=kmax; */
                   4789: /*       } */
                   4790: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4791: /*     k=kmax; l=lmax*10; */
                   4792: /*       } */
                   4793: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4794: /*     delts=delt; */
                   4795: /*       } */
                   4796: /*     } /\* End loop k *\/ */
                   4797: /*   } */
                   4798: /*   delti[theta]=delts; */
                   4799: /*   return res;  */
                   4800: /* } */
                   4801: 
                   4802: 
1.126     brouard  4803: /************** Inverse of matrix **************/
                   4804: void ludcmp(double **a, int n, int *indx, double *d) 
                   4805: { 
                   4806:   int i,imax,j,k; 
                   4807:   double big,dum,sum,temp; 
                   4808:   double *vv; 
                   4809:  
                   4810:   vv=vector(1,n); 
                   4811:   *d=1.0; 
                   4812:   for (i=1;i<=n;i++) { 
                   4813:     big=0.0; 
                   4814:     for (j=1;j<=n;j++) 
                   4815:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4816:     if (big == 0.0){
                   4817:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4818:       for (j=1;j<=n;j++) {
                   4819:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4820:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4821:       }
                   4822:       fflush(ficlog);
                   4823:       fclose(ficlog);
                   4824:       nrerror("Singular matrix in routine ludcmp"); 
                   4825:     }
1.126     brouard  4826:     vv[i]=1.0/big; 
                   4827:   } 
                   4828:   for (j=1;j<=n;j++) { 
                   4829:     for (i=1;i<j;i++) { 
                   4830:       sum=a[i][j]; 
                   4831:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4832:       a[i][j]=sum; 
                   4833:     } 
                   4834:     big=0.0; 
                   4835:     for (i=j;i<=n;i++) { 
                   4836:       sum=a[i][j]; 
                   4837:       for (k=1;k<j;k++) 
                   4838:        sum -= a[i][k]*a[k][j]; 
                   4839:       a[i][j]=sum; 
                   4840:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4841:        big=dum; 
                   4842:        imax=i; 
                   4843:       } 
                   4844:     } 
                   4845:     if (j != imax) { 
                   4846:       for (k=1;k<=n;k++) { 
                   4847:        dum=a[imax][k]; 
                   4848:        a[imax][k]=a[j][k]; 
                   4849:        a[j][k]=dum; 
                   4850:       } 
                   4851:       *d = -(*d); 
                   4852:       vv[imax]=vv[j]; 
                   4853:     } 
                   4854:     indx[j]=imax; 
                   4855:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4856:     if (j != n) { 
                   4857:       dum=1.0/(a[j][j]); 
                   4858:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4859:     } 
                   4860:   } 
                   4861:   free_vector(vv,1,n);  /* Doesn't work */
                   4862: ;
                   4863: } 
                   4864: 
                   4865: void lubksb(double **a, int n, int *indx, double b[]) 
                   4866: { 
                   4867:   int i,ii=0,ip,j; 
                   4868:   double sum; 
                   4869:  
                   4870:   for (i=1;i<=n;i++) { 
                   4871:     ip=indx[i]; 
                   4872:     sum=b[ip]; 
                   4873:     b[ip]=b[i]; 
                   4874:     if (ii) 
                   4875:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4876:     else if (sum) ii=i; 
                   4877:     b[i]=sum; 
                   4878:   } 
                   4879:   for (i=n;i>=1;i--) { 
                   4880:     sum=b[i]; 
                   4881:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4882:     b[i]=sum/a[i][i]; 
                   4883:   } 
                   4884: } 
                   4885: 
                   4886: void pstamp(FILE *fichier)
                   4887: {
1.196     brouard  4888:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4889: }
                   4890: 
1.297     brouard  4891: void date2dmy(double date,double *day, double *month, double *year){
                   4892:   double yp=0., yp1=0., yp2=0.;
                   4893:   
                   4894:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4895:                        fractional in yp1 */
                   4896:   *year=yp;
                   4897:   yp2=modf((yp1*12),&yp);
                   4898:   *month=yp;
                   4899:   yp1=modf((yp2*30.5),&yp);
                   4900:   *day=yp;
                   4901:   if(*day==0) *day=1;
                   4902:   if(*month==0) *month=1;
                   4903: }
                   4904: 
1.253     brouard  4905: 
                   4906: 
1.126     brouard  4907: /************ Frequencies ********************/
1.251     brouard  4908: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4909:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4910:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4911: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  4912:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4913:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4914:   int iind=0, iage=0;
                   4915:   int mi; /* Effective wave */
                   4916:   int first;
                   4917:   double ***freq; /* Frequencies */
1.268     brouard  4918:   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 */
                   4919:   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  4920:   double *meanq, *stdq, *idq;
1.226     brouard  4921:   double **meanqt;
                   4922:   double *pp, **prop, *posprop, *pospropt;
                   4923:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4924:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4925:   double agebegin, ageend;
                   4926:     
                   4927:   pp=vector(1,nlstate);
1.251     brouard  4928:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4929:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4930:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4931:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4932:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4933:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4934:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4935:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4936:   strcpy(fileresp,"P_");
                   4937:   strcat(fileresp,fileresu);
                   4938:   /*strcat(fileresphtm,fileresu);*/
                   4939:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4940:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4941:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4942:     exit(0);
                   4943:   }
1.240     brouard  4944:   
1.226     brouard  4945:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4946:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4947:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4948:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4949:     fflush(ficlog);
                   4950:     exit(70); 
                   4951:   }
                   4952:   else{
                   4953:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4954: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4955: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4956:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4957:   }
1.319     brouard  4958:   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  4959:   
1.226     brouard  4960:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4961:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4962:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4963:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4964:     fflush(ficlog);
                   4965:     exit(70); 
1.240     brouard  4966:   } else{
1.226     brouard  4967:     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  4968: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4969: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4970:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4971:   }
1.319     brouard  4972:   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  4973:   
1.253     brouard  4974:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4975:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4976:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4977:   j1=0;
1.126     brouard  4978:   
1.227     brouard  4979:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.334   ! brouard  4980:   j=cptcoveff;  /* Only dummy covariates used in the model */
1.330     brouard  4981:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4982:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4983:   
                   4984:   
1.226     brouard  4985:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4986:      reference=low_education V1=0,V2=0
                   4987:      med_educ                V1=1 V2=0, 
                   4988:      high_educ               V1=0 V2=1
1.330     brouard  4989:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4990:   */
1.249     brouard  4991:   dateintsum=0;
                   4992:   k2cpt=0;
                   4993: 
1.253     brouard  4994:   if(cptcoveff == 0 )
1.265     brouard  4995:     nl=1;  /* Constant and age model only */
1.253     brouard  4996:   else
                   4997:     nl=2;
1.265     brouard  4998: 
                   4999:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5000:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.330     brouard  5001:    *   Loop on j1(1 to 2**cptcovn) covariate combination
1.265     brouard  5002:    *     freq[s1][s2][iage] =0.
                   5003:    *     Loop on iind
                   5004:    *       ++freq[s1][s2][iage] weighted
                   5005:    *     end iind
                   5006:    *     if covariate and j!0
                   5007:    *       headers Variable on one line
                   5008:    *     endif cov j!=0
                   5009:    *     header of frequency table by age
                   5010:    *     Loop on age
                   5011:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5012:    *       pos+=freq[s1][s2][iage] weighted
                   5013:    *       Loop on s1 initial state
                   5014:    *         fprintf(ficresp
                   5015:    *       end s1
                   5016:    *     end age
                   5017:    *     if j!=0 computes starting values
                   5018:    *     end compute starting values
                   5019:    *   end j1
                   5020:    * end nl 
                   5021:    */
1.253     brouard  5022:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5023:     if(nj==1)
                   5024:       j=0;  /* First pass for the constant */
1.265     brouard  5025:     else{
1.330     brouard  5026:       j=cptcovs; /* Other passes for the covariate values */
1.265     brouard  5027:     }
1.251     brouard  5028:     first=1;
1.332     brouard  5029:     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  5030:       posproptt=0.;
1.330     brouard  5031:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5032:        scanf("%d", i);*/
                   5033:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5034:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5035:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5036:            freq[i][s2][m]=0;
1.251     brouard  5037:       
                   5038:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5039:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5040:          prop[i][m]=0;
                   5041:        posprop[i]=0;
                   5042:        pospropt[i]=0;
                   5043:       }
1.283     brouard  5044:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5045:         idq[z1]=0.;
                   5046:         meanq[z1]=0.;
                   5047:         stdq[z1]=0.;
1.283     brouard  5048:       }
                   5049:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5050:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5051:       /*         meanqt[m][z1]=0.; */
                   5052:       /*       } */
                   5053:       /* }       */
1.251     brouard  5054:       /* dateintsum=0; */
                   5055:       /* k2cpt=0; */
                   5056:       
1.265     brouard  5057:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5058:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5059:        bool=1;
                   5060:        if(j !=0){
                   5061:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.330     brouard  5062:            if (cptcovn >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5063:              for (z1=1; z1<=cptcovn; z1++) { /* loops on covariates in the model */
1.251     brouard  5064:                /* if(Tvaraff[z1] ==-20){ */
                   5065:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5066:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5067:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5068:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.332     brouard  5069:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5070:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5071:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5072:                  /* 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", */
                   5073:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5074:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5075:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5076:                } /* Onlyf fixed */
                   5077:              } /* end z1 */
                   5078:            } /* cptcovn > 0 */
                   5079:          } /* end any */
                   5080:        }/* end j==0 */
1.265     brouard  5081:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5082:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5083:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5084:            m=mw[mi][iind];
                   5085:            if(j!=0){
                   5086:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.330     brouard  5087:                for (z1=1; z1<=cptcovn; z1++) {
1.251     brouard  5088:                  if( Fixed[Tmodelind[z1]]==1){
                   5089:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5090:                    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  5091:                                                                                      value is -1, we don't select. It differs from the 
                   5092:                                                                                      constant and age model which counts them. */
                   5093:                      bool=0; /* not selected */
                   5094:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334   ! brouard  5095:                    /* i1=Tvaraff[z1]; */
        !          5096:                    /* i2=TnsdVar[i1]; */
        !          5097:                    /* i3=nbcode[i1][i2]; */
        !          5098:                    /* i4=covar[i1][iind]; */
        !          5099:                    /* if(i4 != i3){ */
        !          5100:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5101:                      bool=0;
                   5102:                    }
                   5103:                  }
                   5104:                }
                   5105:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5106:            } /* end j==0 */
                   5107:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5108:            if(bool==1){ /*Selected */
1.251     brouard  5109:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5110:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5111:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5112:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5113:              if(m >=firstpass && m <=lastpass){
                   5114:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5115:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5116:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5117:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5118:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5119:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5120:                if (m<lastpass) {
                   5121:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5122:                  /*   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]); */
                   5123:                  if(s[m][iind]==-1)
                   5124:                    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.));
                   5125:                  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  5126:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5127:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5128:                      idq[z1]=idq[z1]+weight[iind];
                   5129:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5130:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5131:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5132:                    }
1.284     brouard  5133:                  }
1.251     brouard  5134:                  /* if((int)agev[m][iind] == 55) */
                   5135:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5136:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5137:                  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  5138:                }
1.251     brouard  5139:              } /* end if between passes */  
                   5140:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5141:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5142:                k2cpt++;
                   5143:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5144:              }
1.251     brouard  5145:            }else{
                   5146:              bool=1;
                   5147:            }/* end bool 2 */
                   5148:          } /* end m */
1.284     brouard  5149:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5150:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5151:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5152:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5153:          /* } */
1.251     brouard  5154:        } /* end bool */
                   5155:       } /* end iind = 1 to imx */
1.319     brouard  5156:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5157:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5158:       
                   5159:       
                   5160:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.330     brouard  5161:       if(cptcovn==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5162:         pstamp(ficresp);
1.330     brouard  5163:       if  (cptcovn>0 && j!=0){
1.265     brouard  5164:         pstamp(ficresp);
1.251     brouard  5165:        printf( "\n#********** Variable "); 
                   5166:        fprintf(ficresp, "\n#********** Variable "); 
                   5167:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5168:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5169:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5170:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5171:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5172:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5173:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5174:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5175:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5176:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5177:          }else{
1.330     brouard  5178:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5179:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5180:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5181:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5182:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5183:          }
                   5184:        }
                   5185:        printf( "**********\n#");
                   5186:        fprintf(ficresp, "**********\n#");
                   5187:        fprintf(ficresphtm, "**********</h3>\n");
                   5188:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5189:        fprintf(ficlog, "**********\n");
                   5190:       }
1.284     brouard  5191:       /*
                   5192:        Printing means of quantitative variables if any
                   5193:       */
                   5194:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5195:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5196:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5197:        if(weightopt==1){
                   5198:          printf(" Weighted mean and standard deviation of");
                   5199:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5200:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5201:        }
1.311     brouard  5202:        /* mu = \frac{w x}{\sum w}
                   5203:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5204:        */
                   5205:        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]));
                   5206:        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]));
                   5207:        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  5208:       }
                   5209:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5210:       /*       for(m=1;m<=lastpass;m++){ */
                   5211:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5212:       /*   } */
                   5213:       /* } */
1.283     brouard  5214: 
1.251     brouard  5215:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.330     brouard  5216:       if((cptcovn==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5217:         fprintf(ficresp, " Age");
1.332     brouard  5218:       if(nj==2) for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5219:       for(i=1; i<=nlstate;i++) {
1.330     brouard  5220:        if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5221:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5222:       }
1.330     brouard  5223:       if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5224:       fprintf(ficresphtm, "\n");
                   5225:       
                   5226:       /* Header of frequency table by age */
                   5227:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5228:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5229:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5230:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5231:          if(s2!=0 && m!=0)
                   5232:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5233:        }
1.226     brouard  5234:       }
1.251     brouard  5235:       fprintf(ficresphtmfr, "\n");
                   5236:     
                   5237:       /* For each age */
                   5238:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5239:        fprintf(ficresphtm,"<tr>");
                   5240:        if(iage==iagemax+1){
                   5241:          fprintf(ficlog,"1");
                   5242:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5243:        }else if(iage==iagemax+2){
                   5244:          fprintf(ficlog,"0");
                   5245:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5246:        }else if(iage==iagemax+3){
                   5247:          fprintf(ficlog,"Total");
                   5248:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5249:        }else{
1.240     brouard  5250:          if(first==1){
1.251     brouard  5251:            first=0;
                   5252:            printf("See log file for details...\n");
                   5253:          }
                   5254:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5255:          fprintf(ficlog,"Age %d", iage);
                   5256:        }
1.265     brouard  5257:        for(s1=1; s1 <=nlstate ; s1++){
                   5258:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5259:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5260:        }
1.265     brouard  5261:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5262:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5263:            pos += freq[s1][m][iage];
                   5264:          if(pp[s1]>=1.e-10){
1.251     brouard  5265:            if(first==1){
1.265     brouard  5266:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5267:            }
1.265     brouard  5268:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5269:          }else{
                   5270:            if(first==1)
1.265     brouard  5271:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5272:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5273:          }
                   5274:        }
                   5275:       
1.265     brouard  5276:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5277:          /* posprop[s1]=0; */
                   5278:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5279:            pp[s1] += freq[s1][m][iage];
                   5280:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5281:       
                   5282:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5283:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5284:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5285:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5286:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5287:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5288:        }
                   5289:        
                   5290:        /* Writing ficresp */
1.330     brouard  5291:        if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5292:           if( iage <= iagemax){
                   5293:            fprintf(ficresp," %d",iage);
                   5294:           }
                   5295:         }else if( nj==2){
                   5296:           if( iage <= iagemax){
                   5297:            fprintf(ficresp," %d",iage);
1.332     brouard  5298:             for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5299:           }
1.240     brouard  5300:        }
1.265     brouard  5301:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5302:          if(pos>=1.e-5){
1.251     brouard  5303:            if(first==1)
1.265     brouard  5304:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5305:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5306:          }else{
                   5307:            if(first==1)
1.265     brouard  5308:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5309:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5310:          }
                   5311:          if( iage <= iagemax){
                   5312:            if(pos>=1.e-5){
1.330     brouard  5313:              if(cptcovn==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5314:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5315:               }else if( nj==2){
                   5316:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5317:               }
                   5318:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5319:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5320:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5321:            } else{
1.330     brouard  5322:              if((cptcovn==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5323:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5324:            }
1.240     brouard  5325:          }
1.265     brouard  5326:          pospropt[s1] +=posprop[s1];
                   5327:        } /* end loop s1 */
1.251     brouard  5328:        /* pospropt=0.; */
1.265     brouard  5329:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5330:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5331:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5332:              if(first==1){
1.265     brouard  5333:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5334:              }
1.265     brouard  5335:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5336:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5337:            }
1.265     brouard  5338:            if(s1!=0 && m!=0)
                   5339:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5340:          }
1.265     brouard  5341:        } /* end loop s1 */
1.251     brouard  5342:        posproptt=0.; 
1.265     brouard  5343:        for(s1=1; s1 <=nlstate; s1++){
                   5344:          posproptt += pospropt[s1];
1.251     brouard  5345:        }
                   5346:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5347:        fprintf(ficresphtm,"</tr>\n");
1.330     brouard  5348:        if((cptcovn==0 && nj==1)|| nj==2 ) {
1.265     brouard  5349:          if(iage <= iagemax)
                   5350:            fprintf(ficresp,"\n");
1.240     brouard  5351:        }
1.251     brouard  5352:        if(first==1)
                   5353:          printf("Others in log...\n");
                   5354:        fprintf(ficlog,"\n");
                   5355:       } /* end loop age iage */
1.265     brouard  5356:       
1.251     brouard  5357:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5358:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5359:        if(posproptt < 1.e-5){
1.265     brouard  5360:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5361:        }else{
1.265     brouard  5362:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5363:        }
1.226     brouard  5364:       }
1.251     brouard  5365:       fprintf(ficresphtm,"</tr>\n");
                   5366:       fprintf(ficresphtm,"</table>\n");
                   5367:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5368:       if(posproptt < 1.e-5){
1.251     brouard  5369:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5370:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5371:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5372:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5373:        invalidvarcomb[j1]=1;
1.226     brouard  5374:       }else{
1.251     brouard  5375:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5376:        invalidvarcomb[j1]=0;
1.226     brouard  5377:       }
1.251     brouard  5378:       fprintf(ficresphtmfr,"</table>\n");
                   5379:       fprintf(ficlog,"\n");
                   5380:       if(j!=0){
                   5381:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5382:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5383:          for(k=1; k <=(nlstate+ndeath); k++){
                   5384:            if (k != i) {
1.265     brouard  5385:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5386:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5387:                  if(j1==1){ /* All dummy covariates to zero */
                   5388:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5389:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5390:                    printf("%d%d ",i,k);
                   5391:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5392:                    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]));
                   5393:                    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]));
                   5394:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5395:                  }
1.253     brouard  5396:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5397:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5398:                    x[iage]= (double)iage;
                   5399:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5400:                    /* 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  5401:                  }
1.268     brouard  5402:                  /* Some are not finite, but linreg will ignore these ages */
                   5403:                  no=0;
1.253     brouard  5404:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5405:                  pstart[s1]=b;
                   5406:                  pstart[s1-1]=a;
1.252     brouard  5407:                }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 */ 
                   5408:                  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]);
                   5409:                  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  5410:                  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  5411:                  printf("%d%d ",i,k);
                   5412:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5413:                  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  5414:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5415:                  ;
                   5416:                }
                   5417:                /* printf("%12.7f )", param[i][jj][k]); */
                   5418:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5419:                s1++; 
1.251     brouard  5420:              } /* end jj */
                   5421:            } /* end k!= i */
                   5422:          } /* end k */
1.265     brouard  5423:        } /* end i, s1 */
1.251     brouard  5424:       } /* end j !=0 */
                   5425:     } /* end selected combination of covariate j1 */
                   5426:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5427:       printf("#Freqsummary: Starting values for the constants:\n");
                   5428:       fprintf(ficlog,"\n");
1.265     brouard  5429:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5430:        for(k=1; k <=(nlstate+ndeath); k++){
                   5431:          if (k != i) {
                   5432:            printf("%d%d ",i,k);
                   5433:            fprintf(ficlog,"%d%d ",i,k);
                   5434:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5435:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5436:              if(jj==1){ /* Age has to be done */
1.265     brouard  5437:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5438:                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]));
                   5439:                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  5440:              }
                   5441:              /* printf("%12.7f )", param[i][jj][k]); */
                   5442:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5443:              s1++; 
1.250     brouard  5444:            }
1.251     brouard  5445:            printf("\n");
                   5446:            fprintf(ficlog,"\n");
1.250     brouard  5447:          }
                   5448:        }
1.284     brouard  5449:       } /* end of state i */
1.251     brouard  5450:       printf("#Freqsummary\n");
                   5451:       fprintf(ficlog,"\n");
1.265     brouard  5452:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5453:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5454:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5455:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5456:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5457:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5458:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5459:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5460:          /* } */
                   5461:        }
1.265     brouard  5462:       } /* end loop s1 */
1.251     brouard  5463:       
                   5464:       printf("\n");
                   5465:       fprintf(ficlog,"\n");
                   5466:     } /* end j=0 */
1.249     brouard  5467:   } /* end j */
1.252     brouard  5468: 
1.253     brouard  5469:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5470:     for(i=1, jk=1; i <=nlstate; i++){
                   5471:       for(j=1; j <=nlstate+ndeath; j++){
                   5472:        if(j!=i){
                   5473:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5474:          printf("%1d%1d",i,j);
                   5475:          fprintf(ficparo,"%1d%1d",i,j);
                   5476:          for(k=1; k<=ncovmodel;k++){
                   5477:            /*    printf(" %lf",param[i][j][k]); */
                   5478:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5479:            p[jk]=pstart[jk];
                   5480:            printf(" %f ",pstart[jk]);
                   5481:            fprintf(ficparo," %f ",pstart[jk]);
                   5482:            jk++;
                   5483:          }
                   5484:          printf("\n");
                   5485:          fprintf(ficparo,"\n");
                   5486:        }
                   5487:       }
                   5488:     }
                   5489:   } /* end mle=-2 */
1.226     brouard  5490:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5491:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5492:   
1.226     brouard  5493:   fclose(ficresp);
                   5494:   fclose(ficresphtm);
                   5495:   fclose(ficresphtmfr);
1.283     brouard  5496:   free_vector(idq,1,nqfveff);
1.226     brouard  5497:   free_vector(meanq,1,nqfveff);
1.284     brouard  5498:   free_vector(stdq,1,nqfveff);
1.226     brouard  5499:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5500:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5501:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5502:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5503:   free_vector(pospropt,1,nlstate);
                   5504:   free_vector(posprop,1,nlstate);
1.251     brouard  5505:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5506:   free_vector(pp,1,nlstate);
                   5507:   /* End of freqsummary */
                   5508: }
1.126     brouard  5509: 
1.268     brouard  5510: /* Simple linear regression */
                   5511: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5512: 
                   5513:   /* y=a+bx regression */
                   5514:   double   sumx = 0.0;                        /* sum of x                      */
                   5515:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5516:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5517:   double   sumy = 0.0;                        /* sum of y                      */
                   5518:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5519:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5520:   double yhat;
                   5521:   
                   5522:   double denom=0;
                   5523:   int i;
                   5524:   int ne=*no;
                   5525:   
                   5526:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5527:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5528:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5529:       continue;
                   5530:     }
                   5531:     ne=ne+1;
                   5532:     sumx  += x[i];       
                   5533:     sumx2 += x[i]*x[i];  
                   5534:     sumxy += x[i] * y[i];
                   5535:     sumy  += y[i];      
                   5536:     sumy2 += y[i]*y[i]; 
                   5537:     denom = (ne * sumx2 - sumx*sumx);
                   5538:     /* 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); */
                   5539:   } 
                   5540:   
                   5541:   denom = (ne * sumx2 - sumx*sumx);
                   5542:   if (denom == 0) {
                   5543:     // vertical, slope m is infinity
                   5544:     *b = INFINITY;
                   5545:     *a = 0;
                   5546:     if (r) *r = 0;
                   5547:     return 1;
                   5548:   }
                   5549:   
                   5550:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5551:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5552:   if (r!=NULL) {
                   5553:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5554:       sqrt((sumx2 - sumx*sumx/ne) *
                   5555:           (sumy2 - sumy*sumy/ne));
                   5556:   }
                   5557:   *no=ne;
                   5558:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5559:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5560:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5561:       continue;
                   5562:     }
                   5563:     ne=ne+1;
                   5564:     yhat = y[i] - *a -*b* x[i];
                   5565:     sume2  += yhat * yhat ;       
                   5566:     
                   5567:     denom = (ne * sumx2 - sumx*sumx);
                   5568:     /* 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); */
                   5569:   } 
                   5570:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5571:   *sa= *sb * sqrt(sumx2/ne);
                   5572:   
                   5573:   return 0; 
                   5574: }
                   5575: 
1.126     brouard  5576: /************ Prevalence ********************/
1.227     brouard  5577: 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)
                   5578: {  
                   5579:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5580:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5581:      We still use firstpass and lastpass as another selection.
                   5582:   */
1.126     brouard  5583:  
1.227     brouard  5584:   int i, m, jk, j1, bool, z1,j, iv;
                   5585:   int mi; /* Effective wave */
                   5586:   int iage;
                   5587:   double agebegin, ageend;
                   5588: 
                   5589:   double **prop;
                   5590:   double posprop; 
                   5591:   double  y2; /* in fractional years */
                   5592:   int iagemin, iagemax;
                   5593:   int first; /** to stop verbosity which is redirected to log file */
                   5594: 
                   5595:   iagemin= (int) agemin;
                   5596:   iagemax= (int) agemax;
                   5597:   /*pp=vector(1,nlstate);*/
1.251     brouard  5598:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5599:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5600:   j1=0;
1.222     brouard  5601:   
1.227     brouard  5602:   /*j=cptcoveff;*/
                   5603:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5604:   
1.288     brouard  5605:   first=0;
1.227     brouard  5606:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   5607:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5608:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5609:        prop[i][iage]=0.0;
                   5610:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5611:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5612:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5613:     
                   5614:     for (i=1; i<=imx; i++) { /* Each individual */
                   5615:       bool=1;
                   5616:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5617:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5618:        m=mw[mi][i];
                   5619:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5620:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5621:        for (z1=1; z1<=cptcoveff; z1++){
                   5622:          if( Fixed[Tmodelind[z1]]==1){
                   5623:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5624:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5625:              bool=0;
                   5626:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5627:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5628:              bool=0;
                   5629:            }
                   5630:        }
                   5631:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5632:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5633:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5634:          if(m >=firstpass && m <=lastpass){
                   5635:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5636:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5637:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5638:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5639:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5640:                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); 
                   5641:                exit(1);
                   5642:              }
                   5643:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5644:                /*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]]);*/
                   5645:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5646:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5647:              } /* end valid statuses */ 
                   5648:            } /* end selection of dates */
                   5649:          } /* end selection of waves */
                   5650:        } /* end bool */
                   5651:       } /* end wave */
                   5652:     } /* end individual */
                   5653:     for(i=iagemin; i <= iagemax+3; i++){  
                   5654:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5655:        posprop += prop[jk][i]; 
                   5656:       } 
                   5657:       
                   5658:       for(jk=1; jk <=nlstate ; jk++){      
                   5659:        if( i <=  iagemax){ 
                   5660:          if(posprop>=1.e-5){ 
                   5661:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5662:          } else{
1.288     brouard  5663:            if(!first){
                   5664:              first=1;
1.266     brouard  5665:              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]);
                   5666:            }else{
1.288     brouard  5667:              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  5668:            }
                   5669:          }
                   5670:        } 
                   5671:       }/* end jk */ 
                   5672:     }/* end i */ 
1.222     brouard  5673:      /*} *//* end i1 */
1.227     brouard  5674:   } /* end j1 */
1.222     brouard  5675:   
1.227     brouard  5676:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5677:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5678:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5679: }  /* End of prevalence */
1.126     brouard  5680: 
                   5681: /************* Waves Concatenation ***************/
                   5682: 
                   5683: 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)
                   5684: {
1.298     brouard  5685:   /* 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  5686:      Death is a valid wave (if date is known).
                   5687:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5688:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5689:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5690:   */
1.126     brouard  5691: 
1.224     brouard  5692:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5693:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5694:      double sum=0., jmean=0.;*/
1.224     brouard  5695:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5696:   int j, k=0,jk, ju, jl;
                   5697:   double sum=0.;
                   5698:   first=0;
1.214     brouard  5699:   firstwo=0;
1.217     brouard  5700:   firsthree=0;
1.218     brouard  5701:   firstfour=0;
1.164     brouard  5702:   jmin=100000;
1.126     brouard  5703:   jmax=-1;
                   5704:   jmean=0.;
1.224     brouard  5705: 
                   5706: /* Treating live states */
1.214     brouard  5707:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5708:     mi=0;  /* First valid wave */
1.227     brouard  5709:     mli=0; /* Last valid wave */
1.309     brouard  5710:     m=firstpass;  /* Loop on waves */
                   5711:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5712:       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 */
                   5713:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5714:       }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  5715:        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  5716:        mli=m;
1.224     brouard  5717:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5718:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5719:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5720:       }
1.309     brouard  5721:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5722: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5723:        break;
1.224     brouard  5724: #else
1.317     brouard  5725:        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  5726:          if(firsthree == 0){
1.302     brouard  5727:            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  5728:            firsthree=1;
1.317     brouard  5729:          }else if(firsthree >=1 && firsthree < 10){
                   5730:            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);
                   5731:            firsthree++;
                   5732:          }else if(firsthree == 10){
                   5733:            printf("Information, too many Information flags: no more reported to log either\n");
                   5734:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5735:            firsthree++;
                   5736:          }else{
                   5737:            firsthree++;
1.227     brouard  5738:          }
1.309     brouard  5739:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5740:          mli=m;
                   5741:        }
                   5742:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5743:          nbwarn++;
1.309     brouard  5744:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5745:            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);
                   5746:            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);
                   5747:          }
                   5748:          break;
                   5749:        }
                   5750:        break;
1.224     brouard  5751: #endif
1.227     brouard  5752:       }/* End m >= lastpass */
1.126     brouard  5753:     }/* end while */
1.224     brouard  5754: 
1.227     brouard  5755:     /* 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  5756:     /* After last pass */
1.224     brouard  5757: /* Treating death states */
1.214     brouard  5758:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5759:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5760:       /* } */
1.126     brouard  5761:       mi++;    /* Death is another wave */
                   5762:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5763:       /* Only death is a correct wave */
1.126     brouard  5764:       mw[mi][i]=m;
1.257     brouard  5765:     } /* else not in a death state */
1.224     brouard  5766: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5767:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5768:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5769:        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  5770:          nbwarn++;
                   5771:          if(firstfiv==0){
1.309     brouard  5772:            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  5773:            firstfiv=1;
                   5774:          }else{
1.309     brouard  5775:            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  5776:          }
1.309     brouard  5777:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5778:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5779:          nberr++;
                   5780:          if(firstwo==0){
1.309     brouard  5781:            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  5782:            firstwo=1;
                   5783:          }
1.309     brouard  5784:          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  5785:        }
1.257     brouard  5786:       }else{ /* if date of interview is unknown */
1.227     brouard  5787:        /* death is known but not confirmed by death status at any wave */
                   5788:        if(firstfour==0){
1.309     brouard  5789:          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  5790:          firstfour=1;
                   5791:        }
1.309     brouard  5792:        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  5793:       }
1.224     brouard  5794:     } /* end if date of death is known */
                   5795: #endif
1.309     brouard  5796:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5797:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5798:     if(mi==0){
                   5799:       nbwarn++;
                   5800:       if(first==0){
1.227     brouard  5801:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5802:        first=1;
1.126     brouard  5803:       }
                   5804:       if(first==1){
1.227     brouard  5805:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5806:       }
                   5807:     } /* end mi==0 */
                   5808:   } /* End individuals */
1.214     brouard  5809:   /* wav and mw are no more changed */
1.223     brouard  5810:        
1.317     brouard  5811:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5812:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5813: 
                   5814: 
1.126     brouard  5815:   for(i=1; i<=imx; i++){
                   5816:     for(mi=1; mi<wav[i];mi++){
                   5817:       if (stepm <=0)
1.227     brouard  5818:        dh[mi][i]=1;
1.126     brouard  5819:       else{
1.260     brouard  5820:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5821:          if (agedc[i] < 2*AGESUP) {
                   5822:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5823:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5824:            else if(j<0){
                   5825:              nberr++;
                   5826:              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]);
                   5827:              j=1; /* Temporary Dangerous patch */
                   5828:              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);
                   5829:              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]);
                   5830:              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);
                   5831:            }
                   5832:            k=k+1;
                   5833:            if (j >= jmax){
                   5834:              jmax=j;
                   5835:              ijmax=i;
                   5836:            }
                   5837:            if (j <= jmin){
                   5838:              jmin=j;
                   5839:              ijmin=i;
                   5840:            }
                   5841:            sum=sum+j;
                   5842:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5843:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5844:          }
                   5845:        }
                   5846:        else{
                   5847:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5848: /*       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  5849:                                        
1.227     brouard  5850:          k=k+1;
                   5851:          if (j >= jmax) {
                   5852:            jmax=j;
                   5853:            ijmax=i;
                   5854:          }
                   5855:          else if (j <= jmin){
                   5856:            jmin=j;
                   5857:            ijmin=i;
                   5858:          }
                   5859:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5860:          /*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]);*/
                   5861:          if(j<0){
                   5862:            nberr++;
                   5863:            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]);
                   5864:            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]);
                   5865:          }
                   5866:          sum=sum+j;
                   5867:        }
                   5868:        jk= j/stepm;
                   5869:        jl= j -jk*stepm;
                   5870:        ju= j -(jk+1)*stepm;
                   5871:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5872:          if(jl==0){
                   5873:            dh[mi][i]=jk;
                   5874:            bh[mi][i]=0;
                   5875:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5876:                  * to avoid the price of an extra matrix product in likelihood */
                   5877:            dh[mi][i]=jk+1;
                   5878:            bh[mi][i]=ju;
                   5879:          }
                   5880:        }else{
                   5881:          if(jl <= -ju){
                   5882:            dh[mi][i]=jk;
                   5883:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5884:                                 * is higher than the multiple of stepm and negative otherwise.
                   5885:                                 */
                   5886:          }
                   5887:          else{
                   5888:            dh[mi][i]=jk+1;
                   5889:            bh[mi][i]=ju;
                   5890:          }
                   5891:          if(dh[mi][i]==0){
                   5892:            dh[mi][i]=1; /* At least one step */
                   5893:            bh[mi][i]=ju; /* At least one step */
                   5894:            /*  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);*/
                   5895:          }
                   5896:        } /* end if mle */
1.126     brouard  5897:       }
                   5898:     } /* end wave */
                   5899:   }
                   5900:   jmean=sum/k;
                   5901:   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  5902:   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  5903: }
1.126     brouard  5904: 
                   5905: /*********** Tricode ****************************/
1.220     brouard  5906:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5907:  {
                   5908:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5909:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5910:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5911:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5912:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5913:     */
1.130     brouard  5914: 
1.242     brouard  5915:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5916:    int modmaxcovj=0; /* Modality max of covariates j */
                   5917:    int cptcode=0; /* Modality max of covariates j */
                   5918:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5919: 
                   5920: 
1.242     brouard  5921:    /* cptcoveff=0;  */
                   5922:    /* *cptcov=0; */
1.126     brouard  5923:  
1.242     brouard  5924:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5925:    for (k=1; k <= maxncov; k++)
                   5926:      for(j=1; j<=2; j++)
                   5927:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5928: 
1.242     brouard  5929:    /* Loop on covariates without age and products and no quantitative variable */
                   5930:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5931:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5932:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5933:        switch(Fixed[k]) {
                   5934:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5935:         modmaxcovj=0;
                   5936:         modmincovj=0;
1.242     brouard  5937:         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*/
                   5938:           ij=(int)(covar[Tvar[k]][i]);
                   5939:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5940:            * If product of Vn*Vm, still boolean *:
                   5941:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5942:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5943:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5944:              modality of the nth covariate of individual i. */
                   5945:           if (ij > modmaxcovj)
                   5946:             modmaxcovj=ij; 
                   5947:           else if (ij < modmincovj) 
                   5948:             modmincovj=ij; 
1.287     brouard  5949:           if (ij <0 || ij >1 ){
1.311     brouard  5950:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5951:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5952:             fflush(ficlog);
                   5953:             exit(1);
1.287     brouard  5954:           }
                   5955:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5956:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5957:             exit(1);
                   5958:           }else
                   5959:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5960:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5961:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5962:           /* getting the maximum value of the modality of the covariate
                   5963:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5964:              female ies 1, then modmaxcovj=1.
                   5965:           */
                   5966:         } /* end for loop on individuals i */
                   5967:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5968:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5969:         cptcode=modmaxcovj;
                   5970:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5971:         /*for (i=0; i<=cptcode; i++) {*/
                   5972:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5973:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5974:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5975:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5976:             if( j != -1){
                   5977:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5978:                                  covariate for which somebody answered excluding 
                   5979:                                  undefined. Usually 2: 0 and 1. */
                   5980:             }
                   5981:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5982:                                     covariate for which somebody answered including 
                   5983:                                     undefined. Usually 3: -1, 0 and 1. */
                   5984:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5985:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5986:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5987:                        
1.242     brouard  5988:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5989:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5990:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5991:         /* modmincovj=3; modmaxcovj = 7; */
                   5992:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5993:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5994:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5995:         /* nbcode[Tvar[j]][ij]=k; */
                   5996:         /* nbcode[Tvar[j]][1]=0; */
                   5997:         /* nbcode[Tvar[j]][2]=1; */
                   5998:         /* nbcode[Tvar[j]][3]=2; */
                   5999:         /* To be continued (not working yet). */
                   6000:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6001: 
                   6002:         /* 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*/
                   6003:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6004:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6005:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6006:         /*, could be restored in the future */
                   6007:         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  6008:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6009:             break;
                   6010:           }
                   6011:           ij++;
1.287     brouard  6012:           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  6013:           cptcode = ij; /* New max modality for covar j */
                   6014:         } /* end of loop on modality i=-1 to 1 or more */
                   6015:         break;
                   6016:        case 1: /* Testing on varying covariate, could be simple and
                   6017:                * should look at waves or product of fixed *
                   6018:                * varying. No time to test -1, assuming 0 and 1 only */
                   6019:         ij=0;
                   6020:         for(i=0; i<=1;i++){
                   6021:           nbcode[Tvar[k]][++ij]=i;
                   6022:         }
                   6023:         break;
                   6024:        default:
                   6025:         break;
                   6026:        } /* end switch */
                   6027:      } /* end dummy test */
1.334   ! brouard  6028:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6029:        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*/
                   6030:         if(isnan(covar[Tvar[k]][i])){
                   6031:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6032:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6033:           fflush(ficlog);
                   6034:           exit(1);
                   6035:          }
                   6036:        }
                   6037:      }
1.287     brouard  6038:    } /* 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  6039:   
                   6040:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6041:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6042:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6043:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6044:      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 */ 
                   6045:      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 */
                   6046:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6047:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6048:   
                   6049:    ij=0;
                   6050:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   6051:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   6052:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6053:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   6054:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   6055:        /* If product not in single variable we don't print results */
                   6056:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6057:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   6058:        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*/
                   6059:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6060:        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 */
                   6061:        if(Fixed[k]!=0)
                   6062:         anyvaryingduminmodel=1;
                   6063:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6064:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6065:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6066:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6067:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6068:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6069:      } 
                   6070:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6071:    /* ij--; */
                   6072:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.330     brouard  6073:    *cptcov=ij; /* cptcov= Number of total real effective covariates: effective (used as cptcoveff in other functions)
1.242     brouard  6074:                * because they can be excluded from the model and real
                   6075:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6076:    for(j=ij+1; j<= cptcovt; j++){
                   6077:      Tvaraff[j]=0;
                   6078:      Tmodelind[j]=0;
                   6079:    }
                   6080:    for(j=ntveff+1; j<= cptcovt; j++){
                   6081:      TmodelInvind[j]=0;
                   6082:    }
                   6083:    /* To be sorted */
                   6084:    ;
                   6085:  }
1.126     brouard  6086: 
1.145     brouard  6087: 
1.126     brouard  6088: /*********** Health Expectancies ****************/
                   6089: 
1.235     brouard  6090:  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  6091: 
                   6092: {
                   6093:   /* Health expectancies, no variances */
1.329     brouard  6094:   /* cij is the combination in the list of combination of dummy covariates */
                   6095:   /* strstart is a string of time at start of computing */
1.164     brouard  6096:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6097:   int nhstepma, nstepma; /* Decreasing with age */
                   6098:   double age, agelim, hf;
                   6099:   double ***p3mat;
                   6100:   double eip;
                   6101: 
1.238     brouard  6102:   /* pstamp(ficreseij); */
1.126     brouard  6103:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6104:   fprintf(ficreseij,"# Age");
                   6105:   for(i=1; i<=nlstate;i++){
                   6106:     for(j=1; j<=nlstate;j++){
                   6107:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6108:     }
                   6109:     fprintf(ficreseij," e%1d. ",i);
                   6110:   }
                   6111:   fprintf(ficreseij,"\n");
                   6112: 
                   6113:   
                   6114:   if(estepm < stepm){
                   6115:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6116:   }
                   6117:   else  hstepm=estepm;   
                   6118:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6119:    * This is mainly to measure the difference between two models: for example
                   6120:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6121:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6122:    * progression in between and thus overestimating or underestimating according
                   6123:    * to the curvature of the survival function. If, for the same date, we 
                   6124:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6125:    * to compare the new estimate of Life expectancy with the same linear 
                   6126:    * hypothesis. A more precise result, taking into account a more precise
                   6127:    * curvature will be obtained if estepm is as small as stepm. */
                   6128: 
                   6129:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6130:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6131:      nhstepm is the number of hstepm from age to agelim 
                   6132:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6133:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6134:      and note for a fixed period like estepm months */
                   6135:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6136:      survival function given by stepm (the optimization length). Unfortunately it
                   6137:      means that if the survival funtion is printed only each two years of age and if
                   6138:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6139:      results. So we changed our mind and took the option of the best precision.
                   6140:   */
                   6141:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6142: 
                   6143:   agelim=AGESUP;
                   6144:   /* If stepm=6 months */
                   6145:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6146:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6147:     
                   6148: /* nhstepm age range expressed in number of stepm */
                   6149:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6150:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6151:   /* if (stepm >= YEARM) hstepm=1;*/
                   6152:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6153:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6154: 
                   6155:   for (age=bage; age<=fage; age ++){ 
                   6156:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6157:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6158:     /* if (stepm >= YEARM) hstepm=1;*/
                   6159:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6160: 
                   6161:     /* If stepm=6 months */
                   6162:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6163:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6164:     /* 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  6165:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6166:     
                   6167:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6168:     
                   6169:     printf("%d|",(int)age);fflush(stdout);
                   6170:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6171:     
                   6172:     /* Computing expectancies */
                   6173:     for(i=1; i<=nlstate;i++)
                   6174:       for(j=1; j<=nlstate;j++)
                   6175:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6176:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6177:          
                   6178:          /* 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]);*/
                   6179: 
                   6180:        }
                   6181: 
                   6182:     fprintf(ficreseij,"%3.0f",age );
                   6183:     for(i=1; i<=nlstate;i++){
                   6184:       eip=0;
                   6185:       for(j=1; j<=nlstate;j++){
                   6186:        eip +=eij[i][j][(int)age];
                   6187:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6188:       }
                   6189:       fprintf(ficreseij,"%9.4f", eip );
                   6190:     }
                   6191:     fprintf(ficreseij,"\n");
                   6192:     
                   6193:   }
                   6194:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6195:   printf("\n");
                   6196:   fprintf(ficlog,"\n");
                   6197:   
                   6198: }
                   6199: 
1.235     brouard  6200:  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  6201: 
                   6202: {
                   6203:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6204:      to initial status i, ei. .
1.126     brouard  6205:   */
                   6206:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6207:   int nhstepma, nstepma; /* Decreasing with age */
                   6208:   double age, agelim, hf;
                   6209:   double ***p3matp, ***p3matm, ***varhe;
                   6210:   double **dnewm,**doldm;
                   6211:   double *xp, *xm;
                   6212:   double **gp, **gm;
                   6213:   double ***gradg, ***trgradg;
                   6214:   int theta;
                   6215: 
                   6216:   double eip, vip;
                   6217: 
                   6218:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6219:   xp=vector(1,npar);
                   6220:   xm=vector(1,npar);
                   6221:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6222:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6223:   
                   6224:   pstamp(ficresstdeij);
                   6225:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6226:   fprintf(ficresstdeij,"# Age");
                   6227:   for(i=1; i<=nlstate;i++){
                   6228:     for(j=1; j<=nlstate;j++)
                   6229:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6230:     fprintf(ficresstdeij," e%1d. ",i);
                   6231:   }
                   6232:   fprintf(ficresstdeij,"\n");
                   6233: 
                   6234:   pstamp(ficrescveij);
                   6235:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6236:   fprintf(ficrescveij,"# Age");
                   6237:   for(i=1; i<=nlstate;i++)
                   6238:     for(j=1; j<=nlstate;j++){
                   6239:       cptj= (j-1)*nlstate+i;
                   6240:       for(i2=1; i2<=nlstate;i2++)
                   6241:        for(j2=1; j2<=nlstate;j2++){
                   6242:          cptj2= (j2-1)*nlstate+i2;
                   6243:          if(cptj2 <= cptj)
                   6244:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6245:        }
                   6246:     }
                   6247:   fprintf(ficrescveij,"\n");
                   6248:   
                   6249:   if(estepm < stepm){
                   6250:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6251:   }
                   6252:   else  hstepm=estepm;   
                   6253:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6254:    * This is mainly to measure the difference between two models: for example
                   6255:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6256:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6257:    * progression in between and thus overestimating or underestimating according
                   6258:    * to the curvature of the survival function. If, for the same date, we 
                   6259:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6260:    * to compare the new estimate of Life expectancy with the same linear 
                   6261:    * hypothesis. A more precise result, taking into account a more precise
                   6262:    * curvature will be obtained if estepm is as small as stepm. */
                   6263: 
                   6264:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6265:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6266:      nhstepm is the number of hstepm from age to agelim 
                   6267:      nstepm is the number of stepm from age to agelin. 
                   6268:      Look at hpijx to understand the reason of that which relies in memory size
                   6269:      and note for a fixed period like estepm months */
                   6270:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6271:      survival function given by stepm (the optimization length). Unfortunately it
                   6272:      means that if the survival funtion is printed only each two years of age and if
                   6273:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6274:      results. So we changed our mind and took the option of the best precision.
                   6275:   */
                   6276:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6277: 
                   6278:   /* If stepm=6 months */
                   6279:   /* nhstepm age range expressed in number of stepm */
                   6280:   agelim=AGESUP;
                   6281:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6282:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6283:   /* if (stepm >= YEARM) hstepm=1;*/
                   6284:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6285:   
                   6286:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6287:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6288:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6289:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6290:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6291:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6292: 
                   6293:   for (age=bage; age<=fage; age ++){ 
                   6294:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6295:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6296:     /* if (stepm >= YEARM) hstepm=1;*/
                   6297:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6298:                
1.126     brouard  6299:     /* If stepm=6 months */
                   6300:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6301:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6302:     
                   6303:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6304:                
1.126     brouard  6305:     /* Computing  Variances of health expectancies */
                   6306:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6307:        decrease memory allocation */
                   6308:     for(theta=1; theta <=npar; theta++){
                   6309:       for(i=1; i<=npar; i++){ 
1.222     brouard  6310:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6311:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6312:       }
1.235     brouard  6313:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6314:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6315:                        
1.126     brouard  6316:       for(j=1; j<= nlstate; j++){
1.222     brouard  6317:        for(i=1; i<=nlstate; i++){
                   6318:          for(h=0; h<=nhstepm-1; h++){
                   6319:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6320:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6321:          }
                   6322:        }
1.126     brouard  6323:       }
1.218     brouard  6324:                        
1.126     brouard  6325:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6326:        for(h=0; h<=nhstepm-1; h++){
                   6327:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6328:        }
1.126     brouard  6329:     }/* End theta */
                   6330:     
                   6331:     
                   6332:     for(h=0; h<=nhstepm-1; h++)
                   6333:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6334:        for(theta=1; theta <=npar; theta++)
                   6335:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6336:     
1.218     brouard  6337:                
1.222     brouard  6338:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6339:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6340:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6341:                
1.222     brouard  6342:     printf("%d|",(int)age);fflush(stdout);
                   6343:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6344:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6345:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6346:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6347:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6348:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6349:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6350:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6351:       }
                   6352:     }
1.320     brouard  6353:     /* if((int)age ==50){ */
                   6354:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6355:     /* } */
1.126     brouard  6356:     /* Computing expectancies */
1.235     brouard  6357:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6358:     for(i=1; i<=nlstate;i++)
                   6359:       for(j=1; j<=nlstate;j++)
1.222     brouard  6360:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6361:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6362:                                        
1.222     brouard  6363:          /* 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  6364:                                        
1.222     brouard  6365:        }
1.269     brouard  6366: 
                   6367:     /* Standard deviation of expectancies ij */                
1.126     brouard  6368:     fprintf(ficresstdeij,"%3.0f",age );
                   6369:     for(i=1; i<=nlstate;i++){
                   6370:       eip=0.;
                   6371:       vip=0.;
                   6372:       for(j=1; j<=nlstate;j++){
1.222     brouard  6373:        eip += eij[i][j][(int)age];
                   6374:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6375:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6376:        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  6377:       }
                   6378:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6379:     }
                   6380:     fprintf(ficresstdeij,"\n");
1.218     brouard  6381:                
1.269     brouard  6382:     /* Variance of expectancies ij */          
1.126     brouard  6383:     fprintf(ficrescveij,"%3.0f",age );
                   6384:     for(i=1; i<=nlstate;i++)
                   6385:       for(j=1; j<=nlstate;j++){
1.222     brouard  6386:        cptj= (j-1)*nlstate+i;
                   6387:        for(i2=1; i2<=nlstate;i2++)
                   6388:          for(j2=1; j2<=nlstate;j2++){
                   6389:            cptj2= (j2-1)*nlstate+i2;
                   6390:            if(cptj2 <= cptj)
                   6391:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6392:          }
1.126     brouard  6393:       }
                   6394:     fprintf(ficrescveij,"\n");
1.218     brouard  6395:                
1.126     brouard  6396:   }
                   6397:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6398:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6399:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6400:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6401:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6402:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6403:   printf("\n");
                   6404:   fprintf(ficlog,"\n");
1.218     brouard  6405:        
1.126     brouard  6406:   free_vector(xm,1,npar);
                   6407:   free_vector(xp,1,npar);
                   6408:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6409:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6410:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6411: }
1.218     brouard  6412:  
1.126     brouard  6413: /************ Variance ******************/
1.235     brouard  6414:  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  6415:  {
1.279     brouard  6416:    /** Variance of health expectancies 
                   6417:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6418:     * double **newm;
                   6419:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6420:     */
1.218     brouard  6421:   
                   6422:    /* int movingaverage(); */
                   6423:    double **dnewm,**doldm;
                   6424:    double **dnewmp,**doldmp;
                   6425:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6426:    int first=0;
1.218     brouard  6427:    int k;
                   6428:    double *xp;
1.279     brouard  6429:    double **gp, **gm;  /**< for var eij */
                   6430:    double ***gradg, ***trgradg; /**< for var eij */
                   6431:    double **gradgp, **trgradgp; /**< for var p point j */
                   6432:    double *gpp, *gmp; /**< for var p point j */
                   6433:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6434:    double ***p3mat;
                   6435:    double age,agelim, hf;
                   6436:    /* double ***mobaverage; */
                   6437:    int theta;
                   6438:    char digit[4];
                   6439:    char digitp[25];
                   6440: 
                   6441:    char fileresprobmorprev[FILENAMELENGTH];
                   6442: 
                   6443:    if(popbased==1){
                   6444:      if(mobilav!=0)
                   6445:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6446:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6447:    }
                   6448:    else 
                   6449:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6450: 
1.218     brouard  6451:    /* if (mobilav!=0) { */
                   6452:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6453:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6454:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6455:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6456:    /*   } */
                   6457:    /* } */
                   6458: 
                   6459:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6460:    sprintf(digit,"%-d",ij);
                   6461:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6462:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6463:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6464:    strcat(fileresprobmorprev,fileresu);
                   6465:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6466:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6467:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6468:    }
                   6469:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6470:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6471:    pstamp(ficresprobmorprev);
                   6472:    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  6473:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.334   ! brouard  6474:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.332     brouard  6475:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  6476:    }
                   6477:    for(j=1;j<=cptcoveff;j++) 
1.334   ! brouard  6478:      fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]);
1.238     brouard  6479:    fprintf(ficresprobmorprev,"\n");
                   6480: 
1.218     brouard  6481:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6482:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6483:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6484:      for(i=1; i<=nlstate;i++)
                   6485:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6486:    }  
                   6487:    fprintf(ficresprobmorprev,"\n");
                   6488:   
                   6489:    fprintf(ficgp,"\n# Routine varevsij");
                   6490:    fprintf(ficgp,"\nunset title \n");
                   6491:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6492:    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");
                   6493:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6494: 
1.218     brouard  6495:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6496:    pstamp(ficresvij);
                   6497:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6498:    if(popbased==1)
                   6499:      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);
                   6500:    else
                   6501:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6502:    fprintf(ficresvij,"# Age");
                   6503:    for(i=1; i<=nlstate;i++)
                   6504:      for(j=1; j<=nlstate;j++)
                   6505:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6506:    fprintf(ficresvij,"\n");
                   6507: 
                   6508:    xp=vector(1,npar);
                   6509:    dnewm=matrix(1,nlstate,1,npar);
                   6510:    doldm=matrix(1,nlstate,1,nlstate);
                   6511:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6512:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6513: 
                   6514:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6515:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6516:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6517:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6518:   
1.218     brouard  6519:    if(estepm < stepm){
                   6520:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6521:    }
                   6522:    else  hstepm=estepm;   
                   6523:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6524:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6525:       nhstepm is the number of hstepm from age to agelim 
                   6526:       nstepm is the number of stepm from age to agelim. 
                   6527:       Look at function hpijx to understand why because of memory size limitations, 
                   6528:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6529:       survival function given by stepm (the optimization length). Unfortunately it
                   6530:       means that if the survival funtion is printed every two years of age and if
                   6531:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6532:       results. So we changed our mind and took the option of the best precision.
                   6533:    */
                   6534:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6535:    agelim = AGESUP;
                   6536:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6537:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6538:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6539:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6540:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6541:      gp=matrix(0,nhstepm,1,nlstate);
                   6542:      gm=matrix(0,nhstepm,1,nlstate);
                   6543:                
                   6544:                
                   6545:      for(theta=1; theta <=npar; theta++){
                   6546:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6547:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6548:        }
1.279     brouard  6549:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6550:        * returns into prlim .
1.288     brouard  6551:        */
1.242     brouard  6552:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6553: 
                   6554:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6555:        if (popbased==1) {
                   6556:         if(mobilav ==0){
                   6557:           for(i=1; i<=nlstate;i++)
                   6558:             prlim[i][i]=probs[(int)age][i][ij];
                   6559:         }else{ /* mobilav */ 
                   6560:           for(i=1; i<=nlstate;i++)
                   6561:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6562:         }
                   6563:        }
1.295     brouard  6564:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6565:        */                      
                   6566:        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  6567:        /**< 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  6568:        * at horizon h in state j including mortality.
                   6569:        */
1.218     brouard  6570:        for(j=1; j<= nlstate; j++){
                   6571:         for(h=0; h<=nhstepm; h++){
                   6572:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6573:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6574:         }
                   6575:        }
1.279     brouard  6576:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6577:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6578:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6579:        */
                   6580:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6581:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6582:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6583:        }
                   6584:        
                   6585:        /* Again with minus shift */
1.218     brouard  6586:                        
                   6587:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6588:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6589: 
1.242     brouard  6590:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6591:                        
                   6592:        if (popbased==1) {
                   6593:         if(mobilav ==0){
                   6594:           for(i=1; i<=nlstate;i++)
                   6595:             prlim[i][i]=probs[(int)age][i][ij];
                   6596:         }else{ /* mobilav */ 
                   6597:           for(i=1; i<=nlstate;i++)
                   6598:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6599:         }
                   6600:        }
                   6601:                        
1.235     brouard  6602:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6603:                        
                   6604:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6605:         for(h=0; h<=nhstepm; h++){
                   6606:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6607:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6608:         }
                   6609:        }
                   6610:        /* This for computing probability of death (h=1 means
                   6611:          computed over hstepm matrices product = hstepm*stepm months) 
                   6612:          as a weighted average of prlim.
                   6613:        */
                   6614:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6615:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6616:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6617:        }    
1.279     brouard  6618:        /* end shifting computations */
                   6619: 
                   6620:        /**< Computing gradient matrix at horizon h 
                   6621:        */
1.218     brouard  6622:        for(j=1; j<= nlstate; j++) /* vareij */
                   6623:         for(h=0; h<=nhstepm; h++){
                   6624:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6625:         }
1.279     brouard  6626:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6627:        */
                   6628:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6629:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6630:        }
                   6631:                        
                   6632:      } /* End theta */
1.279     brouard  6633:      
                   6634:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6635:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6636:                
                   6637:      for(h=0; h<=nhstepm; h++) /* veij */
                   6638:        for(j=1; j<=nlstate;j++)
                   6639:         for(theta=1; theta <=npar; theta++)
                   6640:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6641:                
                   6642:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6643:        for(theta=1; theta <=npar; theta++)
                   6644:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6645:      /**< as well as its transposed matrix 
                   6646:       */               
1.218     brouard  6647:                
                   6648:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6649:      for(i=1;i<=nlstate;i++)
                   6650:        for(j=1;j<=nlstate;j++)
                   6651:         vareij[i][j][(int)age] =0.;
1.279     brouard  6652: 
                   6653:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6654:       * and k (nhstepm) formula 15 of article
                   6655:       * Lievre-Brouard-Heathcote
                   6656:       */
                   6657:      
1.218     brouard  6658:      for(h=0;h<=nhstepm;h++){
                   6659:        for(k=0;k<=nhstepm;k++){
                   6660:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6661:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6662:         for(i=1;i<=nlstate;i++)
                   6663:           for(j=1;j<=nlstate;j++)
                   6664:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6665:        }
                   6666:      }
                   6667:                
1.279     brouard  6668:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6669:       * p.j overall mortality formula 49 but computed directly because
                   6670:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6671:       * wix is independent of theta.
                   6672:       */
1.218     brouard  6673:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6674:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6675:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6676:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6677:         varppt[j][i]=doldmp[j][i];
                   6678:      /* end ppptj */
                   6679:      /*  x centered again */
                   6680:                
1.242     brouard  6681:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6682:                
                   6683:      if (popbased==1) {
                   6684:        if(mobilav ==0){
                   6685:         for(i=1; i<=nlstate;i++)
                   6686:           prlim[i][i]=probs[(int)age][i][ij];
                   6687:        }else{ /* mobilav */ 
                   6688:         for(i=1; i<=nlstate;i++)
                   6689:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6690:        }
                   6691:      }
                   6692:                
                   6693:      /* This for computing probability of death (h=1 means
                   6694:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6695:        as a weighted average of prlim.
                   6696:      */
1.235     brouard  6697:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6698:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6699:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6700:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6701:      }    
                   6702:      /* end probability of death */
                   6703:                
                   6704:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6705:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6706:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6707:        for(i=1; i<=nlstate;i++){
                   6708:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6709:        }
                   6710:      } 
                   6711:      fprintf(ficresprobmorprev,"\n");
                   6712:                
                   6713:      fprintf(ficresvij,"%.0f ",age );
                   6714:      for(i=1; i<=nlstate;i++)
                   6715:        for(j=1; j<=nlstate;j++){
                   6716:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6717:        }
                   6718:      fprintf(ficresvij,"\n");
                   6719:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6720:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6721:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6722:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6723:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6724:    } /* End age */
                   6725:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6726:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6727:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6728:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6729:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6730:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6731:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6732:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6733:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6734:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6735:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6736:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6737:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6738:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6739:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6740:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6741:    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);
                   6742:    /*  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  6743:     */
1.218     brouard  6744:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6745:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6746: 
1.218     brouard  6747:    free_vector(xp,1,npar);
                   6748:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6749:    free_matrix(dnewm,1,nlstate,1,npar);
                   6750:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6751:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6752:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6753:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6754:    fclose(ficresprobmorprev);
                   6755:    fflush(ficgp);
                   6756:    fflush(fichtm); 
                   6757:  }  /* end varevsij */
1.126     brouard  6758: 
                   6759: /************ Variance of prevlim ******************/
1.269     brouard  6760:  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  6761: {
1.205     brouard  6762:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6763:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6764: 
1.268     brouard  6765:   double **dnewmpar,**doldm;
1.126     brouard  6766:   int i, j, nhstepm, hstepm;
                   6767:   double *xp;
                   6768:   double *gp, *gm;
                   6769:   double **gradg, **trgradg;
1.208     brouard  6770:   double **mgm, **mgp;
1.126     brouard  6771:   double age,agelim;
                   6772:   int theta;
                   6773:   
                   6774:   pstamp(ficresvpl);
1.288     brouard  6775:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6776:   fprintf(ficresvpl,"# Age ");
                   6777:   if(nresult >=1)
                   6778:     fprintf(ficresvpl," Result# ");
1.126     brouard  6779:   for(i=1; i<=nlstate;i++)
                   6780:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6781:   fprintf(ficresvpl,"\n");
                   6782: 
                   6783:   xp=vector(1,npar);
1.268     brouard  6784:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6785:   doldm=matrix(1,nlstate,1,nlstate);
                   6786:   
                   6787:   hstepm=1*YEARM; /* Every year of age */
                   6788:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6789:   agelim = AGESUP;
                   6790:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6791:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6792:     if (stepm >= YEARM) hstepm=1;
                   6793:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6794:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6795:     mgp=matrix(1,npar,1,nlstate);
                   6796:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6797:     gp=vector(1,nlstate);
                   6798:     gm=vector(1,nlstate);
                   6799: 
                   6800:     for(theta=1; theta <=npar; theta++){
                   6801:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6802:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6803:       }
1.288     brouard  6804:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6805:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6806:       /* else */
                   6807:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6808:       for(i=1;i<=nlstate;i++){
1.126     brouard  6809:        gp[i] = prlim[i][i];
1.208     brouard  6810:        mgp[theta][i] = prlim[i][i];
                   6811:       }
1.126     brouard  6812:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6813:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6814:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6815:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6816:       /* else */
                   6817:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6818:       for(i=1;i<=nlstate;i++){
1.126     brouard  6819:        gm[i] = prlim[i][i];
1.208     brouard  6820:        mgm[theta][i] = prlim[i][i];
                   6821:       }
1.126     brouard  6822:       for(i=1;i<=nlstate;i++)
                   6823:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6824:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6825:     } /* End theta */
                   6826: 
                   6827:     trgradg =matrix(1,nlstate,1,npar);
                   6828: 
                   6829:     for(j=1; j<=nlstate;j++)
                   6830:       for(theta=1; theta <=npar; theta++)
                   6831:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6832:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6833:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6834:     /*   for(j=1; j<=nlstate;j++){ */
                   6835:     /*         printf(" %d ",j); */
                   6836:     /*         for(theta=1; theta <=npar; theta++) */
                   6837:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6838:     /*         printf("\n "); */
                   6839:     /*   } */
                   6840:     /* } */
                   6841:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6842:     /*   printf("\n gradg %d ",(int)age); */
                   6843:     /*   for(j=1; j<=nlstate;j++){ */
                   6844:     /*         printf("%d ",j); */
                   6845:     /*         for(theta=1; theta <=npar; theta++) */
                   6846:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6847:     /*         printf("\n "); */
                   6848:     /*   } */
                   6849:     /* } */
1.126     brouard  6850: 
                   6851:     for(i=1;i<=nlstate;i++)
                   6852:       varpl[i][(int)age] =0.;
1.209     brouard  6853:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6854:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6855:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6856:     }else{
1.268     brouard  6857:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6858:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6859:     }
1.126     brouard  6860:     for(i=1;i<=nlstate;i++)
                   6861:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6862: 
                   6863:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6864:     if(nresult >=1)
                   6865:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6866:     for(i=1; i<=nlstate;i++){
1.126     brouard  6867:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6868:       /* for(j=1;j<=nlstate;j++) */
                   6869:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6870:     }
1.126     brouard  6871:     fprintf(ficresvpl,"\n");
                   6872:     free_vector(gp,1,nlstate);
                   6873:     free_vector(gm,1,nlstate);
1.208     brouard  6874:     free_matrix(mgm,1,npar,1,nlstate);
                   6875:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6876:     free_matrix(gradg,1,npar,1,nlstate);
                   6877:     free_matrix(trgradg,1,nlstate,1,npar);
                   6878:   } /* End age */
                   6879: 
                   6880:   free_vector(xp,1,npar);
                   6881:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6882:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6883: 
                   6884: }
                   6885: 
                   6886: 
                   6887: /************ Variance of backprevalence limit ******************/
1.269     brouard  6888:  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  6889: {
                   6890:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6891:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6892: 
                   6893:   double **dnewmpar,**doldm;
                   6894:   int i, j, nhstepm, hstepm;
                   6895:   double *xp;
                   6896:   double *gp, *gm;
                   6897:   double **gradg, **trgradg;
                   6898:   double **mgm, **mgp;
                   6899:   double age,agelim;
                   6900:   int theta;
                   6901:   
                   6902:   pstamp(ficresvbl);
                   6903:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6904:   fprintf(ficresvbl,"# Age ");
                   6905:   if(nresult >=1)
                   6906:     fprintf(ficresvbl," Result# ");
                   6907:   for(i=1; i<=nlstate;i++)
                   6908:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6909:   fprintf(ficresvbl,"\n");
                   6910: 
                   6911:   xp=vector(1,npar);
                   6912:   dnewmpar=matrix(1,nlstate,1,npar);
                   6913:   doldm=matrix(1,nlstate,1,nlstate);
                   6914:   
                   6915:   hstepm=1*YEARM; /* Every year of age */
                   6916:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6917:   agelim = AGEINF;
                   6918:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6919:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6920:     if (stepm >= YEARM) hstepm=1;
                   6921:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6922:     gradg=matrix(1,npar,1,nlstate);
                   6923:     mgp=matrix(1,npar,1,nlstate);
                   6924:     mgm=matrix(1,npar,1,nlstate);
                   6925:     gp=vector(1,nlstate);
                   6926:     gm=vector(1,nlstate);
                   6927: 
                   6928:     for(theta=1; theta <=npar; theta++){
                   6929:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6930:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6931:       }
                   6932:       if(mobilavproj > 0 )
                   6933:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6934:       else
                   6935:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6936:       for(i=1;i<=nlstate;i++){
                   6937:        gp[i] = bprlim[i][i];
                   6938:        mgp[theta][i] = bprlim[i][i];
                   6939:       }
                   6940:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6941:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6942:        if(mobilavproj > 0 )
                   6943:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6944:        else
                   6945:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6946:       for(i=1;i<=nlstate;i++){
                   6947:        gm[i] = bprlim[i][i];
                   6948:        mgm[theta][i] = bprlim[i][i];
                   6949:       }
                   6950:       for(i=1;i<=nlstate;i++)
                   6951:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6952:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6953:     } /* End theta */
                   6954: 
                   6955:     trgradg =matrix(1,nlstate,1,npar);
                   6956: 
                   6957:     for(j=1; j<=nlstate;j++)
                   6958:       for(theta=1; theta <=npar; theta++)
                   6959:        trgradg[j][theta]=gradg[theta][j];
                   6960:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6961:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6962:     /*   for(j=1; j<=nlstate;j++){ */
                   6963:     /*         printf(" %d ",j); */
                   6964:     /*         for(theta=1; theta <=npar; theta++) */
                   6965:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6966:     /*         printf("\n "); */
                   6967:     /*   } */
                   6968:     /* } */
                   6969:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6970:     /*   printf("\n gradg %d ",(int)age); */
                   6971:     /*   for(j=1; j<=nlstate;j++){ */
                   6972:     /*         printf("%d ",j); */
                   6973:     /*         for(theta=1; theta <=npar; theta++) */
                   6974:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6975:     /*         printf("\n "); */
                   6976:     /*   } */
                   6977:     /* } */
                   6978: 
                   6979:     for(i=1;i<=nlstate;i++)
                   6980:       varbpl[i][(int)age] =0.;
                   6981:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   6982:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6983:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6984:     }else{
                   6985:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6986:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   6987:     }
                   6988:     for(i=1;i<=nlstate;i++)
                   6989:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6990: 
                   6991:     fprintf(ficresvbl,"%.0f ",age );
                   6992:     if(nresult >=1)
                   6993:       fprintf(ficresvbl,"%d ",nres );
                   6994:     for(i=1; i<=nlstate;i++)
                   6995:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   6996:     fprintf(ficresvbl,"\n");
                   6997:     free_vector(gp,1,nlstate);
                   6998:     free_vector(gm,1,nlstate);
                   6999:     free_matrix(mgm,1,npar,1,nlstate);
                   7000:     free_matrix(mgp,1,npar,1,nlstate);
                   7001:     free_matrix(gradg,1,npar,1,nlstate);
                   7002:     free_matrix(trgradg,1,nlstate,1,npar);
                   7003:   } /* End age */
                   7004: 
                   7005:   free_vector(xp,1,npar);
                   7006:   free_matrix(doldm,1,nlstate,1,npar);
                   7007:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7008: 
                   7009: }
                   7010: 
                   7011: /************ Variance of one-step probabilities  ******************/
                   7012: 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  7013:  {
                   7014:    int i, j=0,  k1, l1, tj;
                   7015:    int k2, l2, j1,  z1;
                   7016:    int k=0, l;
                   7017:    int first=1, first1, first2;
1.326     brouard  7018:    int nres=0; /* New */
1.222     brouard  7019:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7020:    double **dnewm,**doldm;
                   7021:    double *xp;
                   7022:    double *gp, *gm;
                   7023:    double **gradg, **trgradg;
                   7024:    double **mu;
                   7025:    double age, cov[NCOVMAX+1];
                   7026:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7027:    int theta;
                   7028:    char fileresprob[FILENAMELENGTH];
                   7029:    char fileresprobcov[FILENAMELENGTH];
                   7030:    char fileresprobcor[FILENAMELENGTH];
                   7031:    double ***varpij;
                   7032: 
                   7033:    strcpy(fileresprob,"PROB_"); 
                   7034:    strcat(fileresprob,fileres);
                   7035:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7036:      printf("Problem with resultfile: %s\n", fileresprob);
                   7037:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7038:    }
                   7039:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7040:    strcat(fileresprobcov,fileresu);
                   7041:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7042:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7043:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7044:    }
                   7045:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7046:    strcat(fileresprobcor,fileresu);
                   7047:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7048:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7049:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7050:    }
                   7051:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7052:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7053:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7054:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7055:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7056:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7057:    pstamp(ficresprob);
                   7058:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7059:    fprintf(ficresprob,"# Age");
                   7060:    pstamp(ficresprobcov);
                   7061:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7062:    fprintf(ficresprobcov,"# Age");
                   7063:    pstamp(ficresprobcor);
                   7064:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7065:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7066: 
                   7067: 
1.222     brouard  7068:    for(i=1; i<=nlstate;i++)
                   7069:      for(j=1; j<=(nlstate+ndeath);j++){
                   7070:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7071:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7072:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7073:      }  
                   7074:    /* fprintf(ficresprob,"\n");
                   7075:       fprintf(ficresprobcov,"\n");
                   7076:       fprintf(ficresprobcor,"\n");
                   7077:    */
                   7078:    xp=vector(1,npar);
                   7079:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7080:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7081:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7082:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7083:    first=1;
                   7084:    fprintf(ficgp,"\n# Routine varprob");
                   7085:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7086:    fprintf(fichtm,"\n");
                   7087: 
1.288     brouard  7088:    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  7089:    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);
                   7090:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7091: and drawn. It helps understanding how is the covariance between two incidences.\
                   7092:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7093:    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  7094: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7095: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7096: standard deviations wide on each axis. <br>\
                   7097:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7098:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7099: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7100: 
1.222     brouard  7101:    cov[1]=1;
                   7102:    /* tj=cptcoveff; */
1.225     brouard  7103:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7104:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7105:    j1=0;
1.332     brouard  7106: 
                   7107:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7108:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334   ! brouard  7109:      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  7110:      if(tj != 1 && TKresult[nres]!= j1)
                   7111:        continue;
                   7112: 
                   7113:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7114:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7115:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7116:      if  (cptcovn>0) {
1.334   ! brouard  7117:        fprintf(ficresprob, "\n#********** Variable ");
        !          7118:        fprintf(ficresprobcov, "\n#********** Variable "); 
        !          7119:        fprintf(ficgp, "\n#********** Variable ");
        !          7120:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
        !          7121:        fprintf(ficresprobcor, "\n#********** Variable ");    
        !          7122: 
        !          7123:        /* Including quantitative variables of the resultline to be done */
        !          7124:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
        !          7125:         printf("Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
        !          7126:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
        !          7127:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
        !          7128:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
        !          7129:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
        !          7130:             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  */
        !          7131:             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  */
        !          7132:             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  */
        !          7133:             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  */
        !          7134:             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  */
        !          7135:             fprintf(ficresprob,"fixed ");
        !          7136:             fprintf(ficresprobcov,"fixed ");
        !          7137:             fprintf(ficgp,"fixed ");
        !          7138:             fprintf(fichtmcov,"fixed ");
        !          7139:             fprintf(ficresprobcor,"fixed ");
        !          7140:           }else{
        !          7141:             fprintf(ficresprob,"varyi ");
        !          7142:             fprintf(ficresprobcov,"varyi ");
        !          7143:             fprintf(ficgp,"varyi ");
        !          7144:             fprintf(fichtmcov,"varyi ");
        !          7145:             fprintf(ficresprobcor,"varyi ");
        !          7146:           }
        !          7147:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
        !          7148:           /* For each selected (single) quantitative value */
        !          7149:           fprintf(ficresprob," V%d=%f ",Tvqresult[nres][z1],Tqresult[nres][z1]);
        !          7150:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
        !          7151:             fprintf(ficresprob,"fixed ");
        !          7152:             fprintf(ficresprobcov,"fixed ");
        !          7153:             fprintf(ficgp,"fixed ");
        !          7154:             fprintf(fichtmcov,"fixed ");
        !          7155:             fprintf(ficresprobcor,"fixed ");
        !          7156:           }else{
        !          7157:             fprintf(ficresprob,"varyi ");
        !          7158:             fprintf(ficresprobcov,"varyi ");
        !          7159:             fprintf(ficgp,"varyi ");
        !          7160:             fprintf(fichtmcov,"varyi ");
        !          7161:             fprintf(ficresprobcor,"varyi ");
        !          7162:           }
        !          7163:         }else{
        !          7164:           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 */
        !          7165:           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 */
        !          7166:           exit(1);
        !          7167:         }
        !          7168:        } /* End loop on variable of this resultline */
        !          7169:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7170:        fprintf(ficresprob, "**********\n#\n");
                   7171:        fprintf(ficresprobcov, "**********\n#\n");
                   7172:        fprintf(ficgp, "**********\n#\n");
                   7173:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7174:        fprintf(ficresprobcor, "**********\n#");    
                   7175:        if(invalidvarcomb[j1]){
                   7176:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7177:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7178:         continue;
                   7179:        }
                   7180:      }
                   7181:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7182:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7183:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7184:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334   ! brouard  7185:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7186:        cov[2]=age;
                   7187:        if(nagesqr==1)
                   7188:         cov[3]= age*age;
1.334   ! brouard  7189:        /* New code end of combination but for each resultline */
        !          7190:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
        !          7191:         if(Typevar[k1]==1){ /* A product with age */
        !          7192:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7193:         }else{
1.334   ! brouard  7194:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7195:         }
1.334   ! brouard  7196:        }/* End of loop on model equation */
        !          7197: /* Old code */
        !          7198:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
        !          7199:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
        !          7200:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
        !          7201:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
        !          7202:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
        !          7203:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
        !          7204:        /*                                                                  * 1  1 1 1 1 */
        !          7205:        /*                                                                  * 2  2 1 1 1 */
        !          7206:        /*                                                                  * 3  1 2 1 1 */
        !          7207:        /*                                                                  *\/ */
        !          7208:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
        !          7209:        /* } */
        !          7210:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
        !          7211:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
        !          7212:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
        !          7213:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
        !          7214:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
        !          7215:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
        !          7216:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
        !          7217:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
        !          7218:        /*         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]); */
        !          7219:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
        !          7220:        /*         /\* exit(1); *\/ */
        !          7221:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
        !          7222:        /*       } */
        !          7223:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
        !          7224:        /* } */
        !          7225:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
        !          7226:        /*       if(Dummy[Tvard[k][1]]==0){ */
        !          7227:        /*         if(Dummy[Tvard[k][2]]==0){ */
        !          7228:        /*           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]])]; */
        !          7229:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          7230:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
        !          7231:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
        !          7232:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
        !          7233:        /*         } */
        !          7234:        /*       }else{ */
        !          7235:        /*         if(Dummy[Tvard[k][2]]==0){ */
        !          7236:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
        !          7237:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
        !          7238:        /*         }else{ */
        !          7239:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
        !          7240:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
        !          7241:        /*         } */
        !          7242:        /*       } */
        !          7243:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
        !          7244:        /* } */                 
1.326     brouard  7245: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7246:        for(theta=1; theta <=npar; theta++){
                   7247:         for(i=1; i<=npar; i++)
                   7248:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7249:                                
1.222     brouard  7250:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7251:                                
1.222     brouard  7252:         k=0;
                   7253:         for(i=1; i<= (nlstate); i++){
                   7254:           for(j=1; j<=(nlstate+ndeath);j++){
                   7255:             k=k+1;
                   7256:             gp[k]=pmmij[i][j];
                   7257:           }
                   7258:         }
1.220     brouard  7259:                                
1.222     brouard  7260:         for(i=1; i<=npar; i++)
                   7261:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7262:                                
1.222     brouard  7263:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7264:         k=0;
                   7265:         for(i=1; i<=(nlstate); i++){
                   7266:           for(j=1; j<=(nlstate+ndeath);j++){
                   7267:             k=k+1;
                   7268:             gm[k]=pmmij[i][j];
                   7269:           }
                   7270:         }
1.220     brouard  7271:                                
1.222     brouard  7272:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7273:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7274:        }
1.126     brouard  7275: 
1.222     brouard  7276:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7277:         for(theta=1; theta <=npar; theta++)
                   7278:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7279:                        
1.222     brouard  7280:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7281:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7282:                        
1.222     brouard  7283:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7284:                        
1.222     brouard  7285:        k=0;
                   7286:        for(i=1; i<=(nlstate); i++){
                   7287:         for(j=1; j<=(nlstate+ndeath);j++){
                   7288:           k=k+1;
                   7289:           mu[k][(int) age]=pmmij[i][j];
                   7290:         }
                   7291:        }
                   7292:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7293:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7294:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7295:                        
1.222     brouard  7296:        /*printf("\n%d ",(int)age);
                   7297:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7298:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7299:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7300:         }*/
1.220     brouard  7301:                        
1.222     brouard  7302:        fprintf(ficresprob,"\n%d ",(int)age);
                   7303:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7304:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7305:                        
1.222     brouard  7306:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7307:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7308:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7309:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7310:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7311:        }
                   7312:        i=0;
                   7313:        for (k=1; k<=(nlstate);k++){
                   7314:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7315:           i++;
                   7316:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7317:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7318:           for (j=1; j<=i;j++){
                   7319:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7320:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7321:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7322:           }
                   7323:         }
                   7324:        }/* end of loop for state */
                   7325:      } /* end of loop for age */
                   7326:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7327:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7328:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7329:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7330:     
                   7331:      /* Confidence intervalle of pij  */
                   7332:      /*
                   7333:        fprintf(ficgp,"\nunset parametric;unset label");
                   7334:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7335:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7336:        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);
                   7337:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7338:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7339:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7340:      */
                   7341:                
                   7342:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7343:      first1=1;first2=2;
                   7344:      for (k2=1; k2<=(nlstate);k2++){
                   7345:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7346:         if(l2==k2) continue;
                   7347:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7348:         for (k1=1; k1<=(nlstate);k1++){
                   7349:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7350:             if(l1==k1) continue;
                   7351:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7352:             if(i<=j) continue;
                   7353:             for (age=bage; age<=fage; age ++){ 
                   7354:               if ((int)age %5==0){
                   7355:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7356:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7357:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7358:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7359:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7360:                 c12=cv12/sqrt(v1*v2);
                   7361:                 /* Computing eigen value of matrix of covariance */
                   7362:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7363:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7364:                 if ((lc2 <0) || (lc1 <0) ){
                   7365:                   if(first2==1){
                   7366:                     first1=0;
                   7367:                     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);
                   7368:                   }
                   7369:                   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);
                   7370:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7371:                   /* lc2=fabs(lc2); */
                   7372:                 }
1.220     brouard  7373:                                                                
1.222     brouard  7374:                 /* Eigen vectors */
1.280     brouard  7375:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7376:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7377:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7378:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7379:                 }else
                   7380:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7381:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7382:                 v21=(lc1-v1)/cv12*v11;
                   7383:                 v12=-v21;
                   7384:                 v22=v11;
                   7385:                 tnalp=v21/v11;
                   7386:                 if(first1==1){
                   7387:                   first1=0;
                   7388:                   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);
                   7389:                 }
                   7390:                 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);
                   7391:                 /*printf(fignu*/
                   7392:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7393:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7394:                 if(first==1){
                   7395:                   first=0;
                   7396:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7397:                   fprintf(ficgp,"\nset parametric;unset label");
                   7398:                   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);
                   7399:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7400:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7401:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7402: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7403:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7404:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7405:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7406:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7407:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7408:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7409:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7410:                   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  7411:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7412:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7413:                 }else{
                   7414:                   first=0;
                   7415:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7416:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7417:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7418:                   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  7419:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7420:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7421:                 }/* if first */
                   7422:               } /* age mod 5 */
                   7423:             } /* end loop age */
                   7424:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7425:             first=1;
                   7426:           } /*l12 */
                   7427:         } /* k12 */
                   7428:        } /*l1 */
                   7429:      }/* k1 */
1.332     brouard  7430:    }  /* loop on combination of covariates j1 */
1.326     brouard  7431:    } /* loop on nres */
1.222     brouard  7432:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7433:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7434:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7435:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7436:    free_vector(xp,1,npar);
                   7437:    fclose(ficresprob);
                   7438:    fclose(ficresprobcov);
                   7439:    fclose(ficresprobcor);
                   7440:    fflush(ficgp);
                   7441:    fflush(fichtmcov);
                   7442:  }
1.126     brouard  7443: 
                   7444: 
                   7445: /******************* Printing html file ***********/
1.201     brouard  7446: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7447:                  int lastpass, int stepm, int weightopt, char model[],\
                   7448:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7449:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7450:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7451:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7452:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7453:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7454:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7455:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7456: </ul>");
1.319     brouard  7457: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7458: /* </ul>", model); */
1.214     brouard  7459:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7460:    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",
                   7461:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7462:    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  7463:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7464:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7465:    fprintf(fichtm,"\
                   7466:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7467:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7468:    fprintf(fichtm,"\
1.217     brouard  7469:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7470:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7471:    fprintf(fichtm,"\
1.288     brouard  7472:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7473:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7474:    fprintf(fichtm,"\
1.288     brouard  7475:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7476:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7477:    fprintf(fichtm,"\
1.211     brouard  7478:  - (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  7479:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7480:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7481:    if(prevfcast==1){
                   7482:      fprintf(fichtm,"\
                   7483:  - Prevalence projections by age and states:                           \
1.201     brouard  7484:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7485:    }
1.126     brouard  7486: 
                   7487: 
1.225     brouard  7488:    m=pow(2,cptcoveff);
1.222     brouard  7489:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7490: 
1.317     brouard  7491:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7492: 
                   7493:    jj1=0;
                   7494: 
                   7495:    fprintf(fichtm," \n<ul>");
                   7496:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7497:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7498:      if(m != 1 && TKresult[nres]!= k1)
                   7499:        continue;
                   7500:      jj1++;
                   7501:      if (cptcovn > 0) {
                   7502:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7503:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7504:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7505:        }
                   7506:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7507:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7508:        }
                   7509:        fprintf(fichtm,"\">");
                   7510:        
                   7511:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7512:        fprintf(fichtm,"************ Results for covariates");
                   7513:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7514:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7515:        }
                   7516:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7517:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7518:        }
                   7519:        if(invalidvarcomb[k1]){
                   7520:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7521:         continue;
                   7522:        }
                   7523:        fprintf(fichtm,"</a></li>");
                   7524:      } /* cptcovn >0 */
                   7525:    }
1.317     brouard  7526:    fprintf(fichtm," \n</ul>");
1.264     brouard  7527: 
1.222     brouard  7528:    jj1=0;
1.237     brouard  7529: 
                   7530:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7531:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7532:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7533:        continue;
1.220     brouard  7534: 
1.222     brouard  7535:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7536:      jj1++;
                   7537:      if (cptcovn > 0) {
1.264     brouard  7538:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7539:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7540:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7541:        }
                   7542:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7543:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7544:        }
                   7545:        fprintf(fichtm,"\"</a>");
                   7546:  
1.222     brouard  7547:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7548:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7549:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7550:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7551:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7552:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7553:        }
1.237     brouard  7554:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7555:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7556:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7557:       }
                   7558:        
1.230     brouard  7559:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7560:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7561:        if(invalidvarcomb[k1]){
                   7562:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7563:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7564:         continue;
                   7565:        }
                   7566:      }
                   7567:      /* aij, bij */
1.259     brouard  7568:      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  7569: <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  7570:      /* Pij */
1.241     brouard  7571:      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> \
                   7572: <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  7573:      /* Quasi-incidences */
                   7574:      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  7575:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7576:  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  7577: 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> \
                   7578: <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  7579:      /* Survival functions (period) in state j */
                   7580:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7581:        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);
                   7582:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7583:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7584:      }
                   7585:      /* State specific survival functions (period) */
                   7586:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7587:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7588:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7589:  <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);
                   7590:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7591:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7592:      }
1.288     brouard  7593:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7594:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7595:        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);
                   7596:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7597:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7598:      }
1.296     brouard  7599:      if(prevbcast==1){
1.288     brouard  7600:        /* Backward prevalence in each health state */
1.222     brouard  7601:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7602:         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  7603: <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  7604:        }
1.217     brouard  7605:      }
1.222     brouard  7606:      if(prevfcast==1){
1.288     brouard  7607:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7608:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7609:         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);
                   7610:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7611:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7612:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7613:        }
                   7614:      }
1.296     brouard  7615:      if(prevbcast==1){
1.268     brouard  7616:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7617:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7618:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7619:  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 \
                   7620:  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  7621: 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);
                   7622:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7623:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7624:        }
                   7625:      }
1.220     brouard  7626:         
1.222     brouard  7627:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7628:        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);
                   7629:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7630:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7631:      }
                   7632:      /* } /\* end i1 *\/ */
                   7633:    }/* End k1 */
                   7634:    fprintf(fichtm,"</ul>");
1.126     brouard  7635: 
1.222     brouard  7636:    fprintf(fichtm,"\
1.126     brouard  7637: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7638:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7639:  - 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  7640: But because parameters are usually highly correlated (a higher incidence of disability \
                   7641: and a higher incidence of recovery can give very close observed transition) it might \
                   7642: be very useful to look not only at linear confidence intervals estimated from the \
                   7643: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7644: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7645: covariance matrix of the one-step probabilities. \
                   7646: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7647: 
1.222     brouard  7648:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7649:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7650:    fprintf(fichtm,"\
1.126     brouard  7651:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7652:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7653: 
1.222     brouard  7654:    fprintf(fichtm,"\
1.126     brouard  7655:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7656:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7657:    fprintf(fichtm,"\
1.126     brouard  7658:  - 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): \
                   7659:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7660:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7661:    fprintf(fichtm,"\
1.126     brouard  7662:  - (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): \
                   7663:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7664:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7665:    fprintf(fichtm,"\
1.288     brouard  7666:  - 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  7667:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7668:    fprintf(fichtm,"\
1.128     brouard  7669:  - 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  7670:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7671:    fprintf(fichtm,"\
1.288     brouard  7672:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7673:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7674: 
                   7675: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7676: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7677: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7678: /*     <br>",fileres,fileres,fileres,fileres); */
                   7679: /*  else  */
                   7680: /*    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  7681:    fflush(fichtm);
1.126     brouard  7682: 
1.225     brouard  7683:    m=pow(2,cptcoveff);
1.222     brouard  7684:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7685: 
1.317     brouard  7686:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7687: 
                   7688:   jj1=0;
                   7689: 
                   7690:    fprintf(fichtm," \n<ul>");
                   7691:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7692:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7693:      if(m != 1 && TKresult[nres]!= k1)
                   7694:        continue;
                   7695:      jj1++;
                   7696:      if (cptcovn > 0) {
                   7697:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7698:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7699:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7700:        }
                   7701:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7702:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7703:        }
                   7704:        fprintf(fichtm,"\">");
                   7705:        
                   7706:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7707:        fprintf(fichtm,"************ Results for covariates");
                   7708:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7709:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7710:        }
                   7711:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7712:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7713:        }
                   7714:        if(invalidvarcomb[k1]){
                   7715:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7716:         continue;
                   7717:        }
                   7718:        fprintf(fichtm,"</a></li>");
                   7719:      } /* cptcovn >0 */
                   7720:    }
                   7721:    fprintf(fichtm," \n</ul>");
                   7722: 
1.222     brouard  7723:    jj1=0;
1.237     brouard  7724: 
1.241     brouard  7725:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7726:    for(k1=1; k1<=m;k1++){
1.253     brouard  7727:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7728:        continue;
1.222     brouard  7729:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7730:      jj1++;
1.126     brouard  7731:      if (cptcovn > 0) {
1.317     brouard  7732:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7733:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7734:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7735:        }
                   7736:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7737:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7738:        }
                   7739:        fprintf(fichtm,"\"</a>");
                   7740:        
1.126     brouard  7741:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7742:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7743:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7744:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7745:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7746:        }
1.237     brouard  7747:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7748:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7749:       }
                   7750: 
1.321     brouard  7751:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7752: 
1.222     brouard  7753:        if(invalidvarcomb[k1]){
                   7754:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7755:         continue;
                   7756:        }
1.126     brouard  7757:      }
                   7758:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7759:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7760: 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);
                   7761:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7762:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7763:      }
                   7764:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7765: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7766: true period expectancies (those weighted with period prevalences are also\
                   7767:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7768:  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);
                   7769:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7770:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7771:      /* } /\* end i1 *\/ */
                   7772:    }/* End k1 */
1.241     brouard  7773:   }/* End nres */
1.222     brouard  7774:    fprintf(fichtm,"</ul>");
                   7775:    fflush(fichtm);
1.126     brouard  7776: }
                   7777: 
                   7778: /******************* Gnuplot file **************/
1.296     brouard  7779: 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  7780: 
                   7781:   char dirfileres[132],optfileres[132];
1.264     brouard  7782:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7783:   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  7784:   int lv=0, vlv=0, kl=0;
1.130     brouard  7785:   int ng=0;
1.201     brouard  7786:   int vpopbased;
1.223     brouard  7787:   int ioffset; /* variable offset for columns */
1.270     brouard  7788:   int iyearc=1; /* variable column for year of projection  */
                   7789:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7790:   int nres=0; /* Index of resultline */
1.266     brouard  7791:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7792: 
1.126     brouard  7793: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7794: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7795: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7796: /*   } */
                   7797: 
                   7798:   /*#ifdef windows */
                   7799:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7800:   /*#endif */
1.225     brouard  7801:   m=pow(2,cptcoveff);
1.126     brouard  7802: 
1.274     brouard  7803:   /* diagram of the model */
                   7804:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7805:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7806:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7807:   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);
                   7808: 
                   7809:   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);
                   7810:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7811:   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);
                   7812:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7813:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7814:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7815:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7816: 
1.202     brouard  7817:   /* Contribution to likelihood */
                   7818:   /* Plot the probability implied in the likelihood */
1.223     brouard  7819:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7820:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7821:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7822:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7823: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7824:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7825: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7826:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7827:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7828:   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));
                   7829:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7830:   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));
                   7831:   for (i=1; i<= nlstate ; i ++) {
                   7832:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7833:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7834:     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);
                   7835:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7836:       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);
                   7837:     }
                   7838:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7839:   }
                   7840:   /* 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 */               
                   7841:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7842:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7843:   fprintf(ficgp,"\nset out;unset log\n");
                   7844:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7845: 
1.126     brouard  7846:   strcpy(dirfileres,optionfilefiname);
                   7847:   strcpy(optfileres,"vpl");
1.223     brouard  7848:   /* 1eme*/
1.238     brouard  7849:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7850:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7851:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7852:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7853:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7854:          continue;
                   7855:        /* We are interested in selected combination by the resultline */
1.246     brouard  7856:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7857:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7858:        strcpy(gplotlabel,"(");
1.238     brouard  7859:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.332     brouard  7860:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the value of the covariate corresponding to k1 combination *\/ */
                   7861:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7862:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7863:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7864:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7865:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7866:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7867:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7868:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7869:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7870:        }
                   7871:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7872:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7873:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7874:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7875:        }
                   7876:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7877:        /* printf("\n#\n"); */
1.238     brouard  7878:        fprintf(ficgp,"\n#\n");
                   7879:        if(invalidvarcomb[k1]){
1.260     brouard  7880:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7881:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7882:          continue;
                   7883:        }
1.235     brouard  7884:       
1.241     brouard  7885:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7886:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7887:        /* 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  7888:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7889:        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);
                   7890:        /* 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); */
                   7891:       /* k1-1 error should be nres-1*/
1.238     brouard  7892:        for (i=1; i<= nlstate ; i ++) {
                   7893:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7894:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7895:        }
1.288     brouard  7896:        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  7897:        for (i=1; i<= nlstate ; i ++) {
                   7898:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7899:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7900:        } 
1.260     brouard  7901:        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  7902:        for (i=1; i<= nlstate ; i ++) {
                   7903:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7904:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7905:        }  
1.265     brouard  7906:        /* 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)); */
                   7907:        
                   7908:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7909:         if(cptcoveff ==0){
1.271     brouard  7910:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7911:        }else{
                   7912:          kl=0;
                   7913:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7914:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7915:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7916:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7917:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7918:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7919:            vlv= nbcode[Tvaraff[k]][lv];
                   7920:            kl++;
                   7921:            /* 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 *\/ */
                   7922:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7923:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7924:            /* ''  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*/
                   7925:            if(k==cptcoveff){
                   7926:              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], \
                   7927:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7928:            }else{
                   7929:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7930:              kl++;
                   7931:            }
                   7932:          } /* end covariate */
                   7933:        } /* end if no covariate */
                   7934: 
1.296     brouard  7935:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7936:          /* 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  7937:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7938:          if(cptcoveff ==0){
1.245     brouard  7939:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7940:          }else{
                   7941:            kl=0;
                   7942:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7943:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7944:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7945:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7946:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7947:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  7948:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   7949:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7950:              kl++;
1.238     brouard  7951:              /* 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 *\/ */
                   7952:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7953:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7954:              /* ''  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*/
                   7955:              if(k==cptcoveff){
1.245     brouard  7956:                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  7957:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7958:              }else{
1.332     brouard  7959:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  7960:                kl++;
                   7961:              }
                   7962:            } /* end covariate */
                   7963:          } /* end if no covariate */
1.296     brouard  7964:          if(prevbcast == 1){
1.268     brouard  7965:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7966:            /* k1-1 error should be nres-1*/
                   7967:            for (i=1; i<= nlstate ; i ++) {
                   7968:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7969:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7970:            }
1.271     brouard  7971:            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  7972:            for (i=1; i<= nlstate ; i ++) {
                   7973:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7974:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7975:            } 
1.276     brouard  7976:            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  7977:            for (i=1; i<= nlstate ; i ++) {
                   7978:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7979:              else fprintf(ficgp," %%*lf (%%*lf)");
                   7980:            } 
1.274     brouard  7981:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  7982:          } /* end if backprojcast */
1.296     brouard  7983:        } /* end if prevbcast */
1.276     brouard  7984:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   7985:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  7986:       } /* nres */
1.201     brouard  7987:     } /* k1 */
                   7988:   } /* cpt */
1.235     brouard  7989: 
                   7990:   
1.126     brouard  7991:   /*2 eme*/
1.238     brouard  7992:   for (k1=1; k1<= m ; k1 ++){  
                   7993:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7994:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7995:        continue;
                   7996:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  7997:       strcpy(gplotlabel,"(");
1.238     brouard  7998:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  7999:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8000:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.223     brouard  8001:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8002:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8003:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8004:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8005:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8006:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8007:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8008:       }
1.237     brouard  8009:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  8010:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8011:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  8012:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8013:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  8014:       }
1.264     brouard  8015:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8016:       fprintf(ficgp,"\n#\n");
1.223     brouard  8017:       if(invalidvarcomb[k1]){
                   8018:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8019:        continue;
                   8020:       }
1.219     brouard  8021:                        
1.241     brouard  8022:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8023:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8024:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8025:        if(vpopbased==0){
1.238     brouard  8026:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8027:        }else
1.238     brouard  8028:          fprintf(ficgp,"\nreplot ");
                   8029:        for (i=1; i<= nlstate+1 ; i ++) {
                   8030:          k=2*i;
1.261     brouard  8031:          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  8032:          for (j=1; j<= nlstate+1 ; j ++) {
                   8033:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8034:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8035:          }   
                   8036:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8037:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8038:          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  8039:          for (j=1; j<= nlstate+1 ; j ++) {
                   8040:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8041:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8042:          }   
                   8043:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8044:          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  8045:          for (j=1; j<= nlstate+1 ; j ++) {
                   8046:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8047:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8048:          }   
                   8049:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8050:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8051:        } /* state */
                   8052:       } /* vpopbased */
1.264     brouard  8053:       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  8054:     } /* end nres */
                   8055:   } /* k1 end 2 eme*/
                   8056:        
                   8057:        
                   8058:   /*3eme*/
                   8059:   for (k1=1; k1<= m ; k1 ++){
                   8060:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8061:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  8062:        continue;
                   8063: 
1.332     brouard  8064:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8065:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8066:        strcpy(gplotlabel,"(");
1.238     brouard  8067:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8068:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8069:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.238     brouard  8070:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8071:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8072:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8073:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8074:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8075:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8076:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8077:        }
                   8078:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8079:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
                   8080:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8081:        }       
1.264     brouard  8082:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8083:        fprintf(ficgp,"\n#\n");
                   8084:        if(invalidvarcomb[k1]){
                   8085:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8086:          continue;
                   8087:        }
                   8088:                        
                   8089:        /*       k=2+nlstate*(2*cpt-2); */
                   8090:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8091:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8092:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8093:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8094: 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  8095:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8096:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8097:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8098:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8099:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8100:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8101:                                
1.238     brouard  8102:        */
                   8103:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8104:          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  8105:          /*    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  8106:                                
1.238     brouard  8107:        } 
1.261     brouard  8108:        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  8109:       }
1.264     brouard  8110:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8111:     } /* end nres */
                   8112:   } /* end kl 3eme */
1.126     brouard  8113:   
1.223     brouard  8114:   /* 4eme */
1.201     brouard  8115:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  8116:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   8117:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8118:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  8119:        continue;
1.238     brouard  8120:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8121:        strcpy(gplotlabel,"(");
1.238     brouard  8122:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   8123:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8124:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8125:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8126:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8127:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8128:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8129:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8130:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8131:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8132:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8133:        }
                   8134:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8135:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8136:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8137:        }       
1.264     brouard  8138:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8139:        fprintf(ficgp,"\n#\n");
                   8140:        if(invalidvarcomb[k1]){
                   8141:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8142:          continue;
1.223     brouard  8143:        }
1.238     brouard  8144:       
1.241     brouard  8145:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8146:        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  8147:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8148: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8149:        k=3;
                   8150:        for (i=1; i<= nlstate ; i ++){
                   8151:          if(i==1){
                   8152:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8153:          }else{
                   8154:            fprintf(ficgp,", '' ");
                   8155:          }
                   8156:          l=(nlstate+ndeath)*(i-1)+1;
                   8157:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8158:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8159:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8160:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8161:        } /* nlstate */
1.264     brouard  8162:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8163:       } /* end cpt state*/ 
                   8164:     } /* end nres */
                   8165:   } /* end covariate k1 */  
                   8166: 
1.220     brouard  8167: /* 5eme */
1.201     brouard  8168:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  8169:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   8170:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8171:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  8172:        continue;
1.238     brouard  8173:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8174:        strcpy(gplotlabel,"(");
1.238     brouard  8175:        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);
                   8176:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8177:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8178:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8179:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8180:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8181:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8182:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8183:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8184:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8185:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8186:        }
                   8187:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8188:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8189:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8190:        }       
1.264     brouard  8191:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8192:        fprintf(ficgp,"\n#\n");
                   8193:        if(invalidvarcomb[k1]){
                   8194:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8195:          continue;
                   8196:        }
1.227     brouard  8197:       
1.241     brouard  8198:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8199:        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  8200:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8201: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8202:        k=3;
                   8203:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8204:          if(j==1)
                   8205:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8206:          else
                   8207:            fprintf(ficgp,", '' ");
                   8208:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8209:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8210:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8211:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8212:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8213:        } /* nlstate */
                   8214:        fprintf(ficgp,", '' ");
                   8215:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8216:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8217:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8218:          if(j < nlstate)
                   8219:            fprintf(ficgp,"$%d +",k+l);
                   8220:          else
                   8221:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8222:        }
1.264     brouard  8223:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8224:       } /* end cpt state*/ 
                   8225:     } /* end covariate */  
                   8226:   } /* end nres */
1.227     brouard  8227:   
1.220     brouard  8228: /* 6eme */
1.202     brouard  8229:   /* CV preval stable (period) for each covariate */
1.237     brouard  8230:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8231:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8232:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8233:       continue;
1.255     brouard  8234:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8235:       strcpy(gplotlabel,"(");      
1.288     brouard  8236:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8237:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8238:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8239:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8240:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8241:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8242:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8243:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8244:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8245:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8246:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8247:       }
1.237     brouard  8248:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8249:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8250:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8251:       }        
1.264     brouard  8252:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8253:       fprintf(ficgp,"\n#\n");
1.223     brouard  8254:       if(invalidvarcomb[k1]){
1.227     brouard  8255:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8256:        continue;
1.223     brouard  8257:       }
1.227     brouard  8258:       
1.241     brouard  8259:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8260:       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  8261:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8262: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8263:       k=3; /* Offset */
1.255     brouard  8264:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8265:        if(i==1)
                   8266:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8267:        else
                   8268:          fprintf(ficgp,", '' ");
1.255     brouard  8269:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8270:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8271:        for (j=2; j<= nlstate ; j ++)
                   8272:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8273:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8274:       } /* nlstate */
1.264     brouard  8275:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8276:     } /* end cpt state*/ 
                   8277:   } /* end covariate */  
1.227     brouard  8278:   
                   8279:   
1.220     brouard  8280: /* 7eme */
1.296     brouard  8281:   if(prevbcast == 1){
1.288     brouard  8282:     /* CV backward prevalence  for each covariate */
1.237     brouard  8283:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8284:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8285:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8286:        continue;
1.268     brouard  8287:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8288:        strcpy(gplotlabel,"(");      
1.288     brouard  8289:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8290:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8291:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8292:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8293:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8294:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8295:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8296:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8297:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8298:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8299:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8300:        }
1.237     brouard  8301:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8302:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8303:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8304:        }       
1.264     brouard  8305:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8306:        fprintf(ficgp,"\n#\n");
                   8307:        if(invalidvarcomb[k1]){
                   8308:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8309:          continue;
                   8310:        }
                   8311:        
1.241     brouard  8312:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8313:        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  8314:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8315: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8316:        k=3; /* Offset */
1.268     brouard  8317:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8318:          if(i==1)
                   8319:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8320:          else
                   8321:            fprintf(ficgp,", '' ");
                   8322:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8323:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8324:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8325:          /* 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  8326:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8327:          /* for (j=2; j<= nlstate ; j ++) */
                   8328:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8329:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8330:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8331:        } /* nlstate */
1.264     brouard  8332:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8333:       } /* end cpt state*/ 
                   8334:     } /* end covariate */  
1.296     brouard  8335:   } /* End if prevbcast */
1.218     brouard  8336:   
1.223     brouard  8337:   /* 8eme */
1.218     brouard  8338:   if(prevfcast==1){
1.288     brouard  8339:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8340:     
1.237     brouard  8341:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8342:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8343:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8344:        continue;
1.211     brouard  8345:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8346:        strcpy(gplotlabel,"(");      
1.288     brouard  8347:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8348:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8349:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8350:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8351:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8352:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8353:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8354:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8355:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8356:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8357:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8358:        }
1.237     brouard  8359:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8360:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8361:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8362:        }       
1.264     brouard  8363:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8364:        fprintf(ficgp,"\n#\n");
                   8365:        if(invalidvarcomb[k1]){
                   8366:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8367:          continue;
                   8368:        }
                   8369:        
                   8370:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8371:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8372:        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  8373:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8374: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8375: 
                   8376:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8377:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8378:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8379:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8380:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8381:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8382:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8383:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8384:          if(i==istart){
1.227     brouard  8385:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8386:          }else{
                   8387:            fprintf(ficgp,",\\\n '' ");
                   8388:          }
                   8389:          if(cptcoveff ==0){ /* No covariate */
                   8390:            ioffset=2; /* Age is in 2 */
                   8391:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8392:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8393:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8394:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8395:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8396:            if(i==nlstate+1){
1.270     brouard  8397:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8398:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8399:              fprintf(ficgp,",\\\n '' ");
                   8400:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8401:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8402:                     offyear,                           \
1.268     brouard  8403:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8404:            }else
1.227     brouard  8405:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8406:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8407:          }else{ /* more than 2 covariates */
1.270     brouard  8408:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8409:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8410:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8411:            iyearc=ioffset-1;
                   8412:            iagec=ioffset;
1.227     brouard  8413:            fprintf(ficgp," u %d:(",ioffset); 
                   8414:            kl=0;
                   8415:            strcpy(gplotcondition,"(");
                   8416:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8417:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   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]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8423:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8424:              kl++;
                   8425:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8426:              kl++;
                   8427:              if(k <cptcoveff && cptcoveff>1)
                   8428:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8429:            }
                   8430:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8431:            /* 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 *\/ */
                   8432:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8433:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8434:            /* ''  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*/
                   8435:            if(i==nlstate+1){
1.270     brouard  8436:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8437:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8438:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8439:              fprintf(ficgp," u %d:(",iagec); 
                   8440:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8441:                      iyearc, iagec, offyear,                           \
                   8442:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8443: /*  '' 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  8444:            }else{
                   8445:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8446:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8447:            }
                   8448:          } /* end if covariate */
                   8449:        } /* nlstate */
1.264     brouard  8450:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8451:       } /* end cpt state*/
                   8452:     } /* end covariate */
                   8453:   } /* End if prevfcast */
1.227     brouard  8454:   
1.296     brouard  8455:   if(prevbcast==1){
1.268     brouard  8456:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8457:     
                   8458:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8459:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8460:       if(m != 1 && TKresult[nres]!= k1)
                   8461:        continue;
                   8462:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8463:        strcpy(gplotlabel,"(");      
                   8464:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8465:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8466:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8467:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8468:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8469:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8470:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8471:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8472:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8473:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8474:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8475:        }
                   8476:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8477:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8478:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.268     brouard  8479:        }       
                   8480:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8481:        fprintf(ficgp,"\n#\n");
                   8482:        if(invalidvarcomb[k1]){
                   8483:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8484:          continue;
                   8485:        }
                   8486:        
                   8487:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8488:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8489:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8490:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8491: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8492: 
                   8493:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8494:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8495:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8496:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8497:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8498:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8499:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8500:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8501:          if(i==istart){
                   8502:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8503:          }else{
                   8504:            fprintf(ficgp,",\\\n '' ");
                   8505:          }
                   8506:          if(cptcoveff ==0){ /* No covariate */
                   8507:            ioffset=2; /* Age is in 2 */
                   8508:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8509:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8510:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8511:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8512:            fprintf(ficgp," u %d:(", ioffset); 
                   8513:            if(i==nlstate+1){
1.270     brouard  8514:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8515:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8516:              fprintf(ficgp,",\\\n '' ");
                   8517:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8518:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8519:                     offbyear,                          \
                   8520:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8521:            }else
                   8522:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8523:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8524:          }else{ /* more than 2 covariates */
1.270     brouard  8525:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8526:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8527:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8528:            iyearc=ioffset-1;
                   8529:            iagec=ioffset;
1.268     brouard  8530:            fprintf(ficgp," u %d:(",ioffset); 
                   8531:            kl=0;
                   8532:            strcpy(gplotcondition,"(");
                   8533:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8534:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   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]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8540:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8541:              kl++;
                   8542:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8543:              kl++;
                   8544:              if(k <cptcoveff && cptcoveff>1)
                   8545:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8546:            }
                   8547:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8548:            /* 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 *\/ */
                   8549:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8550:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8551:            /* ''  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*/
                   8552:            if(i==nlstate+1){
1.270     brouard  8553:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8554:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8555:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8556:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8557:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8558:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8559:                      iyearc,iagec,offbyear,                            \
                   8560:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8561: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8562:            }else{
                   8563:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8564:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8565:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8566:            }
                   8567:          } /* end if covariate */
                   8568:        } /* nlstate */
                   8569:        fprintf(ficgp,"\nset out; unset label;\n");
                   8570:       } /* end cpt state*/
                   8571:     } /* end covariate */
1.296     brouard  8572:   } /* End if prevbcast */
1.268     brouard  8573:   
1.227     brouard  8574:   
1.238     brouard  8575:   /* 9eme writing MLE parameters */
                   8576:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8577:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8578:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8579:     for(k=1; k <=(nlstate+ndeath); k++){
                   8580:       if (k != i) {
1.227     brouard  8581:        fprintf(ficgp,"#   current state %d\n",k);
                   8582:        for(j=1; j <=ncovmodel; j++){
                   8583:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8584:          jk++; 
                   8585:        }
                   8586:        fprintf(ficgp,"\n");
1.126     brouard  8587:       }
                   8588:     }
1.223     brouard  8589:   }
1.187     brouard  8590:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8591:   
1.145     brouard  8592:   /*goto avoid;*/
1.238     brouard  8593:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8594:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8595:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8596:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8597:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8598:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8599:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8600:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8601:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8602:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8603:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8604:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8605:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8606:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8607:   fprintf(ficgp,"#\n");
1.223     brouard  8608:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8609:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8610:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8611:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8612:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8613:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8614:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8615:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8616:        continue;
1.264     brouard  8617:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8618:       strcpy(gplotlabel,"(");
1.276     brouard  8619:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8620:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8621:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8622:        lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.264     brouard  8623:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8624:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8625:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8626:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8627:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.264     brouard  8628:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8629:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8630:       }
1.237     brouard  8631:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8632:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8633:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8634:       }        
1.264     brouard  8635:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8636:       fprintf(ficgp,"\n#\n");
1.264     brouard  8637:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8638:       fprintf(ficgp,"\nset key outside ");
                   8639:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8640:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8641:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8642:       if (ng==1){
                   8643:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8644:        fprintf(ficgp,"\nunset log y");
                   8645:       }else if (ng==2){
                   8646:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8647:        fprintf(ficgp,"\nset log y");
                   8648:       }else if (ng==3){
                   8649:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8650:        fprintf(ficgp,"\nset log y");
                   8651:       }else
                   8652:        fprintf(ficgp,"\nunset title ");
                   8653:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8654:       i=1;
                   8655:       for(k2=1; k2<=nlstate; k2++) {
                   8656:        k3=i;
                   8657:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8658:          if (k != k2){
                   8659:            switch( ng) {
                   8660:            case 1:
                   8661:              if(nagesqr==0)
                   8662:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8663:              else /* nagesqr =1 */
                   8664:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8665:              break;
                   8666:            case 2: /* ng=2 */
                   8667:              if(nagesqr==0)
                   8668:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8669:              else /* nagesqr =1 */
                   8670:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8671:              break;
                   8672:            case 3:
                   8673:              if(nagesqr==0)
                   8674:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8675:              else /* nagesqr =1 */
                   8676:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8677:              break;
                   8678:            }
                   8679:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8680:            ijp=1; /* product no age */
                   8681:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8682:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8683:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8684:              switch(Typevar[j]){
                   8685:              case 1:
                   8686:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8687:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8688:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8689:                      if(DummyV[j]==0){/* Bug valgrind */
                   8690:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8691:                      }else{ /* quantitative */
                   8692:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8693:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8694:                      }
                   8695:                      ij++;
1.268     brouard  8696:                    }
1.237     brouard  8697:                  }
1.329     brouard  8698:                }
                   8699:                break;
                   8700:              case 2:
                   8701:                if(cptcovprod >0){
                   8702:                  if(j==Tprod[ijp]) { /* */ 
                   8703:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8704:                    if(ijp <=cptcovprod) { /* Product */
                   8705:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8706:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8707:                          /* 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)]); */
                   8708:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8709:                        }else{ /* Vn is dummy and Vm is quanti */
                   8710:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8711:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8712:                        }
                   8713:                      }else{ /* Vn*Vm Vn is quanti */
                   8714:                        if(DummyV[Tvard[ijp][2]]==0){
                   8715:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8716:                        }else{ /* Both quanti */
                   8717:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8718:                        }
1.268     brouard  8719:                      }
1.329     brouard  8720:                      ijp++;
1.237     brouard  8721:                    }
1.329     brouard  8722:                  } /* end Tprod */
                   8723:                }
                   8724:                break;
                   8725:              case 0:
                   8726:                /* simple covariate */
1.264     brouard  8727:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8728:                if(Dummy[j]==0){
                   8729:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8730:                }else{ /* quantitative */
                   8731:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8732:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8733:                }
1.329     brouard  8734:               /* end simple */
                   8735:                break;
                   8736:              default:
                   8737:                break;
                   8738:              } /* end switch */
1.237     brouard  8739:            } /* end j */
1.329     brouard  8740:          }else{ /* k=k2 */
                   8741:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8742:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8743:            }else
                   8744:              i=i-ncovmodel;
1.223     brouard  8745:          }
1.227     brouard  8746:          
1.223     brouard  8747:          if(ng != 1){
                   8748:            fprintf(ficgp,")/(1");
1.227     brouard  8749:            
1.264     brouard  8750:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8751:              if(nagesqr==0)
1.264     brouard  8752:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8753:              else /* nagesqr =1 */
1.264     brouard  8754:                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  8755:               
1.223     brouard  8756:              ij=1;
1.329     brouard  8757:              ijp=1;
                   8758:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8759:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8760:                switch(Typevar[j]){
                   8761:                case 1:
                   8762:                  if(cptcovage >0){ 
                   8763:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8764:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8765:                        if(DummyV[j]==0){/* Bug valgrind */
                   8766:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8767:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8768:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8769:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8770:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8771:                        }else{ /* quantitative */
                   8772:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8773:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8774:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8775:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8776:                        }
                   8777:                        ij++;
                   8778:                      }
                   8779:                    }
                   8780:                  }
                   8781:                  break;
                   8782:                case 2:
                   8783:                  if(cptcovprod >0){
                   8784:                    if(j==Tprod[ijp]) { /* */ 
                   8785:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8786:                      if(ijp <=cptcovprod) { /* Product */
                   8787:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8788:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8789:                            /* 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)]); */
                   8790:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8791:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8792:                          }else{ /* Vn is dummy and Vm is quanti */
                   8793:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8794:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8795:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8796:                          }
                   8797:                        }else{ /* Vn*Vm Vn is quanti */
                   8798:                          if(DummyV[Tvard[ijp][2]]==0){
                   8799:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8800:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8801:                          }else{ /* Both quanti */
                   8802:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8803:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8804:                          } 
                   8805:                        }
                   8806:                        ijp++;
                   8807:                      }
                   8808:                    } /* end Tprod */
                   8809:                  } /* end if */
                   8810:                  break;
                   8811:                case 0: 
                   8812:                  /* simple covariate */
                   8813:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8814:                  if(Dummy[j]==0){
                   8815:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8816:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8817:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8818:                  }else{ /* quantitative */
                   8819:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8820:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8821:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8822:                  }
                   8823:                  /* end simple */
                   8824:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8825:                  break;
                   8826:                default:
                   8827:                  break;
                   8828:                } /* end switch */
1.223     brouard  8829:              }
                   8830:              fprintf(ficgp,")");
                   8831:            }
                   8832:            fprintf(ficgp,")");
                   8833:            if(ng ==2)
1.276     brouard  8834:              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  8835:            else /* ng= 3 */
1.276     brouard  8836:              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  8837:           }else{ /* end ng <> 1 */
1.223     brouard  8838:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8839:              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  8840:          }
                   8841:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8842:            fprintf(ficgp,",");
                   8843:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8844:            fprintf(ficgp,",");
                   8845:          i=i+ncovmodel;
                   8846:        } /* end k */
                   8847:       } /* end k2 */
1.276     brouard  8848:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8849:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8850:     } /* end k1 */
1.223     brouard  8851:   } /* end ng */
                   8852:   /* avoid: */
                   8853:   fflush(ficgp); 
1.126     brouard  8854: }  /* end gnuplot */
                   8855: 
                   8856: 
                   8857: /*************** Moving average **************/
1.219     brouard  8858: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8859:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8860:    
1.222     brouard  8861:    int i, cpt, cptcod;
                   8862:    int modcovmax =1;
                   8863:    int mobilavrange, mob;
                   8864:    int iage=0;
1.288     brouard  8865:    int firstA1=0, firstA2=0;
1.222     brouard  8866: 
1.266     brouard  8867:    double sum=0., sumr=0.;
1.222     brouard  8868:    double age;
1.266     brouard  8869:    double *sumnewp, *sumnewm, *sumnewmr;
                   8870:    double *agemingood, *agemaxgood; 
                   8871:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8872:   
                   8873:   
1.278     brouard  8874:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8875:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8876: 
                   8877:    sumnewp = vector(1,ncovcombmax);
                   8878:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8879:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8880:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8881:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8882:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8883:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8884: 
                   8885:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8886:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8887:      sumnewp[cptcod]=0.;
1.266     brouard  8888:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8889:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8890:    }
                   8891:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8892:   
1.266     brouard  8893:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8894:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8895:      else mobilavrange=mobilav;
                   8896:      for (age=bage; age<=fage; age++)
                   8897:        for (i=1; i<=nlstate;i++)
                   8898:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8899:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8900:      /* We keep the original values on the extreme ages bage, fage and for 
                   8901:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8902:        we use a 5 terms etc. until the borders are no more concerned. 
                   8903:      */ 
                   8904:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8905:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8906:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8907:           sumnewm[cptcod]=0.;
                   8908:           for (i=1; i<=nlstate;i++){
1.222     brouard  8909:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8910:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8911:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8912:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8913:             }
                   8914:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8915:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8916:           } /* end i */
                   8917:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8918:         } /* end cptcod */
1.222     brouard  8919:        }/* end age */
                   8920:      }/* end mob */
1.266     brouard  8921:    }else{
                   8922:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8923:      return -1;
1.266     brouard  8924:    }
                   8925: 
                   8926:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8927:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8928:      if(invalidvarcomb[cptcod]){
                   8929:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8930:        continue;
                   8931:      }
1.219     brouard  8932: 
1.266     brouard  8933:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8934:        sumnewm[cptcod]=0.;
                   8935:        sumnewmr[cptcod]=0.;
                   8936:        for (i=1; i<=nlstate;i++){
                   8937:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8938:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8939:        }
                   8940:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8941:         agemingoodr[cptcod]=age;
                   8942:        }
                   8943:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8944:           agemingood[cptcod]=age;
                   8945:        }
                   8946:      } /* age */
                   8947:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8948:        sumnewm[cptcod]=0.;
1.266     brouard  8949:        sumnewmr[cptcod]=0.;
1.222     brouard  8950:        for (i=1; i<=nlstate;i++){
                   8951:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8952:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8953:        }
                   8954:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8955:         agemaxgoodr[cptcod]=age;
1.222     brouard  8956:        }
                   8957:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8958:         agemaxgood[cptcod]=age;
                   8959:        }
                   8960:      } /* age */
                   8961:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8962:      /* but they will change */
1.288     brouard  8963:      firstA1=0;firstA2=0;
1.266     brouard  8964:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8965:        sumnewm[cptcod]=0.;
                   8966:        sumnewmr[cptcod]=0.;
                   8967:        for (i=1; i<=nlstate;i++){
                   8968:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8969:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8970:        }
                   8971:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   8972:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8973:           agemaxgoodr[cptcod]=age;  /* age min */
                   8974:           for (i=1; i<=nlstate;i++)
                   8975:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8976:         }else{ /* bad we change the value with the values of good ages */
                   8977:           for (i=1; i<=nlstate;i++){
                   8978:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   8979:           } /* i */
                   8980:         } /* end bad */
                   8981:        }else{
                   8982:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8983:           agemaxgood[cptcod]=age;
                   8984:         }else{ /* bad we change the value with the values of good ages */
                   8985:           for (i=1; i<=nlstate;i++){
                   8986:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   8987:           } /* i */
                   8988:         } /* end bad */
                   8989:        }/* end else */
                   8990:        sum=0.;sumr=0.;
                   8991:        for (i=1; i<=nlstate;i++){
                   8992:         sum+=mobaverage[(int)age][i][cptcod];
                   8993:         sumr+=probs[(int)age][i][cptcod];
                   8994:        }
                   8995:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  8996:         if(!firstA1){
                   8997:           firstA1=1;
                   8998:           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);
                   8999:         }
                   9000:         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  9001:        } /* end bad */
                   9002:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9003:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9004:         if(!firstA2){
                   9005:           firstA2=1;
                   9006:           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);
                   9007:         }
                   9008:         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  9009:        } /* end bad */
                   9010:      }/* age */
1.266     brouard  9011: 
                   9012:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9013:        sumnewm[cptcod]=0.;
1.266     brouard  9014:        sumnewmr[cptcod]=0.;
1.222     brouard  9015:        for (i=1; i<=nlstate;i++){
                   9016:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9017:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9018:        } 
                   9019:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9020:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9021:           agemingoodr[cptcod]=age;
                   9022:           for (i=1; i<=nlstate;i++)
                   9023:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9024:         }else{ /* bad we change the value with the values of good ages */
                   9025:           for (i=1; i<=nlstate;i++){
                   9026:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9027:           } /* i */
                   9028:         } /* end bad */
                   9029:        }else{
                   9030:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9031:           agemingood[cptcod]=age;
                   9032:         }else{ /* bad */
                   9033:           for (i=1; i<=nlstate;i++){
                   9034:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9035:           } /* i */
                   9036:         } /* end bad */
                   9037:        }/* end else */
                   9038:        sum=0.;sumr=0.;
                   9039:        for (i=1; i<=nlstate;i++){
                   9040:         sum+=mobaverage[(int)age][i][cptcod];
                   9041:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9042:        }
1.266     brouard  9043:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9044:         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  9045:        } /* end bad */
                   9046:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9047:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9048:         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  9049:        } /* end bad */
                   9050:      }/* age */
1.266     brouard  9051: 
1.222     brouard  9052:                
                   9053:      for (age=bage; age<=fage; age++){
1.235     brouard  9054:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9055:        sumnewp[cptcod]=0.;
                   9056:        sumnewm[cptcod]=0.;
                   9057:        for (i=1; i<=nlstate;i++){
                   9058:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9059:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9060:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9061:        }
                   9062:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9063:      }
                   9064:      /* printf("\n"); */
                   9065:      /* } */
1.266     brouard  9066: 
1.222     brouard  9067:      /* brutal averaging */
1.266     brouard  9068:      /* for (i=1; i<=nlstate;i++){ */
                   9069:      /*   for (age=1; age<=bage; age++){ */
                   9070:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9071:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9072:      /*   }     */
                   9073:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9074:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9075:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9076:      /*   } */
                   9077:      /* } /\* end i status *\/ */
                   9078:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9079:      /*   for (age=1; age<=AGESUP; age++){ */
                   9080:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9081:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9082:      /*   } */
                   9083:      /* } */
1.222     brouard  9084:    }/* end cptcod */
1.266     brouard  9085:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9086:    free_vector(agemaxgood,1, ncovcombmax);
                   9087:    free_vector(agemingood,1, ncovcombmax);
                   9088:    free_vector(agemingoodr,1, ncovcombmax);
                   9089:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9090:    free_vector(sumnewm,1, ncovcombmax);
                   9091:    free_vector(sumnewp,1, ncovcombmax);
                   9092:    return 0;
                   9093:  }/* End movingaverage */
1.218     brouard  9094:  
1.126     brouard  9095: 
1.296     brouard  9096:  
1.126     brouard  9097: /************** Forecasting ******************/
1.296     brouard  9098: /* 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)*/
                   9099: 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){
                   9100:   /* dateintemean, mean date of interviews
                   9101:      dateprojd, year, month, day of starting projection 
                   9102:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9103:      agemin, agemax range of age
                   9104:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9105:   */
1.296     brouard  9106:   /* double anprojd, mprojd, jprojd; */
                   9107:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9108:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9109:   double agec; /* generic age */
1.296     brouard  9110:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9111:   double *popeffectif,*popcount;
                   9112:   double ***p3mat;
1.218     brouard  9113:   /* double ***mobaverage; */
1.126     brouard  9114:   char fileresf[FILENAMELENGTH];
                   9115: 
                   9116:   agelim=AGESUP;
1.211     brouard  9117:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9118:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9119:      We still use firstpass and lastpass as another selection.
                   9120:   */
1.214     brouard  9121:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9122:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9123:  
1.201     brouard  9124:   strcpy(fileresf,"F_"); 
                   9125:   strcat(fileresf,fileresu);
1.126     brouard  9126:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9127:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9128:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9129:   }
1.235     brouard  9130:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9131:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9132: 
1.225     brouard  9133:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9134: 
                   9135: 
                   9136:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9137:   if (stepm<=12) stepsize=1;
                   9138:   if(estepm < stepm){
                   9139:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9140:   }
1.270     brouard  9141:   else{
                   9142:     hstepm=estepm;   
                   9143:   }
                   9144:   if(estepm > stepm){ /* Yes every two year */
                   9145:     stepsize=2;
                   9146:   }
1.296     brouard  9147:   hstepm=hstepm/stepm;
1.126     brouard  9148: 
1.296     brouard  9149:   
                   9150:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9151:   /*                              fractional in yp1 *\/ */
                   9152:   /* aintmean=yp; */
                   9153:   /* yp2=modf((yp1*12),&yp); */
                   9154:   /* mintmean=yp; */
                   9155:   /* yp1=modf((yp2*30.5),&yp); */
                   9156:   /* jintmean=yp; */
                   9157:   /* if(jintmean==0) jintmean=1; */
                   9158:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9159: 
1.296     brouard  9160: 
                   9161:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9162:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9163:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9164:   i1=pow(2,cptcoveff);
1.126     brouard  9165:   if (cptcovn < 1){i1=1;}
                   9166:   
1.296     brouard  9167:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9168:   
                   9169:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9170:   
1.126     brouard  9171: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9172:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9173:     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  9174:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9175:       continue;
1.227     brouard  9176:     if(invalidvarcomb[k]){
                   9177:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9178:       continue;
                   9179:     }
                   9180:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9181:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9182:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9183:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9184:     }
1.235     brouard  9185:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9186:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9187:     }
1.227     brouard  9188:     fprintf(ficresf," yearproj age");
                   9189:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9190:       for(i=1; i<=nlstate;i++)               
                   9191:        fprintf(ficresf," p%d%d",i,j);
                   9192:       fprintf(ficresf," wp.%d",j);
                   9193:     }
1.296     brouard  9194:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9195:       fprintf(ficresf,"\n");
1.296     brouard  9196:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9197:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9198:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9199:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9200:        nhstepm = nhstepm/hstepm; 
                   9201:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9202:        oldm=oldms;savm=savms;
1.268     brouard  9203:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9204:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9205:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9206:        for (h=0; h<=nhstepm; h++){
                   9207:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9208:            break;
                   9209:          }
                   9210:        }
                   9211:        fprintf(ficresf,"\n");
                   9212:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9213:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9214:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9215:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9216:        
                   9217:        for(j=1; j<=nlstate+ndeath;j++) {
                   9218:          ppij=0.;
                   9219:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9220:            if (mobilav>=1)
                   9221:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9222:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9223:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9224:            }
1.268     brouard  9225:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9226:          } /* end i */
                   9227:          fprintf(ficresf," %.3f", ppij);
                   9228:        }/* end j */
1.227     brouard  9229:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9230:       } /* end agec */
1.266     brouard  9231:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9232:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9233:     } /* end yearp */
                   9234:   } /* end  k */
1.219     brouard  9235:        
1.126     brouard  9236:   fclose(ficresf);
1.215     brouard  9237:   printf("End of Computing forecasting \n");
                   9238:   fprintf(ficlog,"End of Computing forecasting\n");
                   9239: 
1.126     brouard  9240: }
                   9241: 
1.269     brouard  9242: /************** Back Forecasting ******************/
1.296     brouard  9243:  /* 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){ */
                   9244:  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){
                   9245:   /* back1, year, month, day of starting backprojection
1.267     brouard  9246:      agemin, agemax range of age
                   9247:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9248:      anback2 year of end of backprojection (same day and month as back1).
                   9249:      prevacurrent and prev are prevalences.
1.267     brouard  9250:   */
                   9251:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9252:   double agec; /* generic age */
1.302     brouard  9253:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9254:   double *popeffectif,*popcount;
                   9255:   double ***p3mat;
                   9256:   /* double ***mobaverage; */
                   9257:   char fileresfb[FILENAMELENGTH];
                   9258:  
1.268     brouard  9259:   agelim=AGEINF;
1.267     brouard  9260:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9261:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9262:      We still use firstpass and lastpass as another selection.
                   9263:   */
                   9264:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9265:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9266: 
                   9267:   /*Do we need to compute prevalence again?*/
                   9268: 
                   9269:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9270:   
                   9271:   strcpy(fileresfb,"FB_");
                   9272:   strcat(fileresfb,fileresu);
                   9273:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9274:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9275:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9276:   }
                   9277:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9278:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9279:   
                   9280:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9281:   
                   9282:    
                   9283:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9284:   if (stepm<=12) stepsize=1;
                   9285:   if(estepm < stepm){
                   9286:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9287:   }
1.270     brouard  9288:   else{
                   9289:     hstepm=estepm;   
                   9290:   }
                   9291:   if(estepm >= stepm){ /* Yes every two year */
                   9292:     stepsize=2;
                   9293:   }
1.267     brouard  9294:   
                   9295:   hstepm=hstepm/stepm;
1.296     brouard  9296:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9297:   /*                              fractional in yp1 *\/ */
                   9298:   /* aintmean=yp; */
                   9299:   /* yp2=modf((yp1*12),&yp); */
                   9300:   /* mintmean=yp; */
                   9301:   /* yp1=modf((yp2*30.5),&yp); */
                   9302:   /* jintmean=yp; */
                   9303:   /* if(jintmean==0) jintmean=1; */
                   9304:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9305:   
                   9306:   i1=pow(2,cptcoveff);
                   9307:   if (cptcovn < 1){i1=1;}
                   9308:   
1.296     brouard  9309:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9310:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9311:   
                   9312:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9313:   
                   9314:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9315:   for(k=1; k<=i1;k++){
                   9316:     if(i1 != 1 && TKresult[nres]!= k)
                   9317:       continue;
                   9318:     if(invalidvarcomb[k]){
                   9319:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9320:       continue;
                   9321:     }
1.268     brouard  9322:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9323:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9324:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9325:     }
                   9326:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9327:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9328:     }
                   9329:     fprintf(ficresfb," yearbproj age");
                   9330:     for(j=1; j<=nlstate+ndeath;j++){
                   9331:       for(i=1; i<=nlstate;i++)
1.268     brouard  9332:        fprintf(ficresfb," b%d%d",i,j);
                   9333:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9334:     }
1.296     brouard  9335:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9336:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9337:       fprintf(ficresfb,"\n");
1.296     brouard  9338:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9339:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9340:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9341:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9342:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9343:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9344:        nhstepm = nhstepm/hstepm;
                   9345:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9346:        oldm=oldms;savm=savms;
1.268     brouard  9347:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9348:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9349:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9350:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9351:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9352:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9353:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9354:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9355:            break;
                   9356:          }
                   9357:        }
                   9358:        fprintf(ficresfb,"\n");
                   9359:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9360:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9361:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9362:        for(i=1; i<=nlstate+ndeath;i++) {
                   9363:          ppij=0.;ppi=0.;
                   9364:          for(j=1; j<=nlstate;j++) {
                   9365:            /* if (mobilav==1) */
1.269     brouard  9366:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9367:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9368:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9369:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9370:              /* else { */
                   9371:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9372:              /* } */
1.268     brouard  9373:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9374:          } /* end j */
                   9375:          if(ppi <0.99){
                   9376:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9377:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9378:          }
                   9379:          fprintf(ficresfb," %.3f", ppij);
                   9380:        }/* end j */
1.267     brouard  9381:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9382:       } /* end agec */
                   9383:     } /* end yearp */
                   9384:   } /* end k */
1.217     brouard  9385:   
1.267     brouard  9386:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9387:   
1.267     brouard  9388:   fclose(ficresfb);
                   9389:   printf("End of Computing Back forecasting \n");
                   9390:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9391:        
1.267     brouard  9392: }
1.217     brouard  9393: 
1.269     brouard  9394: /* Variance of prevalence limit: varprlim */
                   9395:  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  9396:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9397:  
                   9398:    char fileresvpl[FILENAMELENGTH];  
                   9399:    FILE *ficresvpl;
                   9400:    double **oldm, **savm;
                   9401:    double **varpl; /* Variances of prevalence limits by age */   
                   9402:    int i1, k, nres, j ;
                   9403:    
                   9404:     strcpy(fileresvpl,"VPL_");
                   9405:     strcat(fileresvpl,fileresu);
                   9406:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9407:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9408:       exit(0);
                   9409:     }
1.288     brouard  9410:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9411:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9412:     
                   9413:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9414:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9415:     
                   9416:     i1=pow(2,cptcoveff);
                   9417:     if (cptcovn < 1){i1=1;}
                   9418: 
                   9419:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9420:       for(k=1; k<=i1;k++){ /* We find the combination equivalent to result line values of dummies */
1.269     brouard  9421:       if(i1 != 1 && TKresult[nres]!= k)
                   9422:        continue;
                   9423:       fprintf(ficresvpl,"\n#****** ");
                   9424:       printf("\n#****** ");
                   9425:       fprintf(ficlog,"\n#****** ");
                   9426:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9427:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9428:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9429:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9430:       }
                   9431:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9432:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9433:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9434:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9435:       }        
                   9436:       fprintf(ficresvpl,"******\n");
                   9437:       printf("******\n");
                   9438:       fprintf(ficlog,"******\n");
                   9439:       
                   9440:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9441:       oldm=oldms;savm=savms;
                   9442:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9443:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9444:       /*}*/
                   9445:     }
                   9446:     
                   9447:     fclose(ficresvpl);
1.288     brouard  9448:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9449:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9450: 
                   9451:  }
                   9452: /* Variance of back prevalence: varbprlim */
                   9453:  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){
                   9454:       /*------- Variance of back (stable) prevalence------*/
                   9455: 
                   9456:    char fileresvbl[FILENAMELENGTH];  
                   9457:    FILE  *ficresvbl;
                   9458: 
                   9459:    double **oldm, **savm;
                   9460:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9461:    int i1, k, nres, j ;
                   9462: 
                   9463:    strcpy(fileresvbl,"VBL_");
                   9464:    strcat(fileresvbl,fileresu);
                   9465:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9466:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9467:      exit(0);
                   9468:    }
                   9469:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9470:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9471:    
                   9472:    
                   9473:    i1=pow(2,cptcoveff);
                   9474:    if (cptcovn < 1){i1=1;}
                   9475:    
                   9476:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9477:      for(k=1; k<=i1;k++){
                   9478:        if(i1 != 1 && TKresult[nres]!= k)
                   9479:         continue;
                   9480:        fprintf(ficresvbl,"\n#****** ");
                   9481:        printf("\n#****** ");
                   9482:        fprintf(ficlog,"\n#****** ");
                   9483:        for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9484:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9485:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9486:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9487:        }
                   9488:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9489:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9490:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9491:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9492:        }
                   9493:        fprintf(ficresvbl,"******\n");
                   9494:        printf("******\n");
                   9495:        fprintf(ficlog,"******\n");
                   9496:        
                   9497:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9498:        oldm=oldms;savm=savms;
                   9499:        
                   9500:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9501:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9502:        /*}*/
                   9503:      }
                   9504:    
                   9505:    fclose(ficresvbl);
                   9506:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9507:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9508: 
                   9509:  } /* End of varbprlim */
                   9510: 
1.126     brouard  9511: /************** Forecasting *****not tested NB*************/
1.227     brouard  9512: /* 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  9513:   
1.227     brouard  9514: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9515: /*   int *popage; */
                   9516: /*   double calagedatem, agelim, kk1, kk2; */
                   9517: /*   double *popeffectif,*popcount; */
                   9518: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9519: /*   /\* double ***mobaverage; *\/ */
                   9520: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9521: 
1.227     brouard  9522: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9523: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9524: /*   agelim=AGESUP; */
                   9525: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9526:   
1.227     brouard  9527: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9528:   
                   9529:   
1.227     brouard  9530: /*   strcpy(filerespop,"POP_");  */
                   9531: /*   strcat(filerespop,fileresu); */
                   9532: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9533: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9534: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9535: /*   } */
                   9536: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9537: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9538: 
1.227     brouard  9539: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9540: 
1.227     brouard  9541: /*   /\* if (mobilav!=0) { *\/ */
                   9542: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9543: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9544: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9545: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9546: /*   /\*   } *\/ */
                   9547: /*   /\* } *\/ */
1.126     brouard  9548: 
1.227     brouard  9549: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9550: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9551:   
1.227     brouard  9552: /*   agelim=AGESUP; */
1.126     brouard  9553:   
1.227     brouard  9554: /*   hstepm=1; */
                   9555: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9556:        
1.227     brouard  9557: /*   if (popforecast==1) { */
                   9558: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9559: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9560: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9561: /*     }  */
                   9562: /*     popage=ivector(0,AGESUP); */
                   9563: /*     popeffectif=vector(0,AGESUP); */
                   9564: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9565:     
1.227     brouard  9566: /*     i=1;    */
                   9567: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9568:     
1.227     brouard  9569: /*     imx=i; */
                   9570: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9571: /*   } */
1.218     brouard  9572:   
1.227     brouard  9573: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9574: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9575: /*       k=k+1; */
                   9576: /*       fprintf(ficrespop,"\n#******"); */
                   9577: /*       for(j=1;j<=cptcoveff;j++) { */
                   9578: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9579: /*       } */
                   9580: /*       fprintf(ficrespop,"******\n"); */
                   9581: /*       fprintf(ficrespop,"# Age"); */
                   9582: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9583: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9584:       
1.227     brouard  9585: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9586: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9587:        
1.227     brouard  9588: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9589: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9590: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9591:          
1.227     brouard  9592: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9593: /*       oldm=oldms;savm=savms; */
                   9594: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9595:          
1.227     brouard  9596: /*       for (h=0; h<=nhstepm; h++){ */
                   9597: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9598: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9599: /*         }  */
                   9600: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9601: /*           kk1=0.;kk2=0; */
                   9602: /*           for(i=1; i<=nlstate;i++) {               */
                   9603: /*             if (mobilav==1)  */
                   9604: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9605: /*             else { */
                   9606: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9607: /*             } */
                   9608: /*           } */
                   9609: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9610: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9611: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9612: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9613: /*           } */
                   9614: /*         } */
                   9615: /*         for(i=1; i<=nlstate;i++){ */
                   9616: /*           kk1=0.; */
                   9617: /*           for(j=1; j<=nlstate;j++){ */
                   9618: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9619: /*           } */
                   9620: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9621: /*         } */
1.218     brouard  9622:            
1.227     brouard  9623: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9624: /*           for(j=1; j<=nlstate;j++)  */
                   9625: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9626: /*       } */
                   9627: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9628: /*     } */
                   9629: /*       } */
1.218     brouard  9630:       
1.227     brouard  9631: /*       /\******\/ */
1.218     brouard  9632:       
1.227     brouard  9633: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9634: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9635: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9636: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9637: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9638:          
1.227     brouard  9639: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9640: /*       oldm=oldms;savm=savms; */
                   9641: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9642: /*       for (h=0; h<=nhstepm; h++){ */
                   9643: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9644: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9645: /*         }  */
                   9646: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9647: /*           kk1=0.;kk2=0; */
                   9648: /*           for(i=1; i<=nlstate;i++) {               */
                   9649: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9650: /*           } */
                   9651: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9652: /*         } */
                   9653: /*       } */
                   9654: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9655: /*     } */
                   9656: /*       } */
                   9657: /*     }  */
                   9658: /*   } */
1.218     brouard  9659:   
1.227     brouard  9660: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9661:   
1.227     brouard  9662: /*   if (popforecast==1) { */
                   9663: /*     free_ivector(popage,0,AGESUP); */
                   9664: /*     free_vector(popeffectif,0,AGESUP); */
                   9665: /*     free_vector(popcount,0,AGESUP); */
                   9666: /*   } */
                   9667: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9668: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9669: /*   fclose(ficrespop); */
                   9670: /* } /\* End of popforecast *\/ */
1.218     brouard  9671:  
1.126     brouard  9672: int fileappend(FILE *fichier, char *optionfich)
                   9673: {
                   9674:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9675:     printf("Problem with file: %s\n", optionfich);
                   9676:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9677:     return (0);
                   9678:   }
                   9679:   fflush(fichier);
                   9680:   return (1);
                   9681: }
                   9682: 
                   9683: 
                   9684: /**************** function prwizard **********************/
                   9685: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9686: {
                   9687: 
                   9688:   /* Wizard to print covariance matrix template */
                   9689: 
1.164     brouard  9690:   char ca[32], cb[32];
                   9691:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9692:   int numlinepar;
                   9693: 
                   9694:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9695:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9696:   for(i=1; i <=nlstate; i++){
                   9697:     jj=0;
                   9698:     for(j=1; j <=nlstate+ndeath; j++){
                   9699:       if(j==i) continue;
                   9700:       jj++;
                   9701:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9702:       printf("%1d%1d",i,j);
                   9703:       fprintf(ficparo,"%1d%1d",i,j);
                   9704:       for(k=1; k<=ncovmodel;k++){
                   9705:        /*        printf(" %lf",param[i][j][k]); */
                   9706:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9707:        printf(" 0.");
                   9708:        fprintf(ficparo," 0.");
                   9709:       }
                   9710:       printf("\n");
                   9711:       fprintf(ficparo,"\n");
                   9712:     }
                   9713:   }
                   9714:   printf("# Scales (for hessian or gradient estimation)\n");
                   9715:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9716:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9717:   for(i=1; i <=nlstate; i++){
                   9718:     jj=0;
                   9719:     for(j=1; j <=nlstate+ndeath; j++){
                   9720:       if(j==i) continue;
                   9721:       jj++;
                   9722:       fprintf(ficparo,"%1d%1d",i,j);
                   9723:       printf("%1d%1d",i,j);
                   9724:       fflush(stdout);
                   9725:       for(k=1; k<=ncovmodel;k++){
                   9726:        /*      printf(" %le",delti3[i][j][k]); */
                   9727:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9728:        printf(" 0.");
                   9729:        fprintf(ficparo," 0.");
                   9730:       }
                   9731:       numlinepar++;
                   9732:       printf("\n");
                   9733:       fprintf(ficparo,"\n");
                   9734:     }
                   9735:   }
                   9736:   printf("# Covariance matrix\n");
                   9737: /* # 121 Var(a12)\n\ */
                   9738: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9739: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9740: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9741: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9742: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9743: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9744: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9745:   fflush(stdout);
                   9746:   fprintf(ficparo,"# Covariance matrix\n");
                   9747:   /* # 121 Var(a12)\n\ */
                   9748:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9749:   /* #   ...\n\ */
                   9750:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9751:   
                   9752:   for(itimes=1;itimes<=2;itimes++){
                   9753:     jj=0;
                   9754:     for(i=1; i <=nlstate; i++){
                   9755:       for(j=1; j <=nlstate+ndeath; j++){
                   9756:        if(j==i) continue;
                   9757:        for(k=1; k<=ncovmodel;k++){
                   9758:          jj++;
                   9759:          ca[0]= k+'a'-1;ca[1]='\0';
                   9760:          if(itimes==1){
                   9761:            printf("#%1d%1d%d",i,j,k);
                   9762:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9763:          }else{
                   9764:            printf("%1d%1d%d",i,j,k);
                   9765:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9766:            /*  printf(" %.5le",matcov[i][j]); */
                   9767:          }
                   9768:          ll=0;
                   9769:          for(li=1;li <=nlstate; li++){
                   9770:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9771:              if(lj==li) continue;
                   9772:              for(lk=1;lk<=ncovmodel;lk++){
                   9773:                ll++;
                   9774:                if(ll<=jj){
                   9775:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9776:                  if(ll<jj){
                   9777:                    if(itimes==1){
                   9778:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9779:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9780:                    }else{
                   9781:                      printf(" 0.");
                   9782:                      fprintf(ficparo," 0.");
                   9783:                    }
                   9784:                  }else{
                   9785:                    if(itimes==1){
                   9786:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9787:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9788:                    }else{
                   9789:                      printf(" 0.");
                   9790:                      fprintf(ficparo," 0.");
                   9791:                    }
                   9792:                  }
                   9793:                }
                   9794:              } /* end lk */
                   9795:            } /* end lj */
                   9796:          } /* end li */
                   9797:          printf("\n");
                   9798:          fprintf(ficparo,"\n");
                   9799:          numlinepar++;
                   9800:        } /* end k*/
                   9801:       } /*end j */
                   9802:     } /* end i */
                   9803:   } /* end itimes */
                   9804: 
                   9805: } /* end of prwizard */
                   9806: /******************* Gompertz Likelihood ******************************/
                   9807: double gompertz(double x[])
                   9808: { 
1.302     brouard  9809:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9810:   int i,n=0; /* n is the size of the sample */
                   9811: 
1.220     brouard  9812:   for (i=1;i<=imx ; i++) {
1.126     brouard  9813:     sump=sump+weight[i];
                   9814:     /*    sump=sump+1;*/
                   9815:     num=num+1;
                   9816:   }
1.302     brouard  9817:   L=0.0;
                   9818:   /* agegomp=AGEGOMP; */
1.126     brouard  9819:   /* for (i=0; i<=imx; i++) 
                   9820:      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]);*/
                   9821: 
1.302     brouard  9822:   for (i=1;i<=imx ; i++) {
                   9823:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9824:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9825:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9826:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9827:      * +
                   9828:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9829:      */
                   9830:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9831:        if (cens[i] == 1){
                   9832:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9833:        } else if (cens[i] == 0){
1.126     brouard  9834:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9835:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9836:       } else
                   9837:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9838:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9839:        L=L+A*weight[i];
1.126     brouard  9840:        /*      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  9841:      }
                   9842:   }
1.126     brouard  9843: 
1.302     brouard  9844:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9845:  
                   9846:   return -2*L*num/sump;
                   9847: }
                   9848: 
1.136     brouard  9849: #ifdef GSL
                   9850: /******************* Gompertz_f Likelihood ******************************/
                   9851: double gompertz_f(const gsl_vector *v, void *params)
                   9852: { 
1.302     brouard  9853:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9854:   double *x= (double *) v->data;
                   9855:   int i,n=0; /* n is the size of the sample */
                   9856: 
                   9857:   for (i=0;i<=imx-1 ; i++) {
                   9858:     sump=sump+weight[i];
                   9859:     /*    sump=sump+1;*/
                   9860:     num=num+1;
                   9861:   }
                   9862:  
                   9863:  
                   9864:   /* for (i=0; i<=imx; i++) 
                   9865:      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]);*/
                   9866:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9867:   for (i=1;i<=imx ; i++)
                   9868:     {
                   9869:       if (cens[i] == 1 && wav[i]>1)
                   9870:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9871:       
                   9872:       if (cens[i] == 0 && wav[i]>1)
                   9873:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9874:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9875:       
                   9876:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9877:       if (wav[i] > 1 ) { /* ??? */
                   9878:        LL=LL+A*weight[i];
                   9879:        /*      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]);*/
                   9880:       }
                   9881:     }
                   9882: 
                   9883:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9884:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9885:  
                   9886:   return -2*LL*num/sump;
                   9887: }
                   9888: #endif
                   9889: 
1.126     brouard  9890: /******************* Printing html file ***********/
1.201     brouard  9891: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9892:                  int lastpass, int stepm, int weightopt, char model[],\
                   9893:                  int imx,  double p[],double **matcov,double agemortsup){
                   9894:   int i,k;
                   9895: 
                   9896:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9897:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9898:   for (i=1;i<=2;i++) 
                   9899:     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  9900:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9901:   fprintf(fichtm,"</ul>");
                   9902: 
                   9903: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9904: 
                   9905:  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>");
                   9906: 
                   9907:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9908:    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]);
                   9909: 
                   9910:  
                   9911:   fflush(fichtm);
                   9912: }
                   9913: 
                   9914: /******************* Gnuplot file **************/
1.201     brouard  9915: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9916: 
                   9917:   char dirfileres[132],optfileres[132];
1.164     brouard  9918: 
1.126     brouard  9919:   int ng;
                   9920: 
                   9921: 
                   9922:   /*#ifdef windows */
                   9923:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9924:     /*#endif */
                   9925: 
                   9926: 
                   9927:   strcpy(dirfileres,optionfilefiname);
                   9928:   strcpy(optfileres,"vpl");
1.199     brouard  9929:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9930:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9931:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9932:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9933:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9934: 
                   9935: } 
                   9936: 
1.136     brouard  9937: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9938: {
1.126     brouard  9939: 
1.136     brouard  9940:   /*-------- data file ----------*/
                   9941:   FILE *fic;
                   9942:   char dummy[]="                         ";
1.240     brouard  9943:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9944:   int lstra;
1.136     brouard  9945:   int linei, month, year,iout;
1.302     brouard  9946:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9947:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9948:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9949:   char *stratrunc;
1.223     brouard  9950: 
1.240     brouard  9951:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9952:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9953:   for(v=1;v<NCOVMAX;v++){
                   9954:     DummyV[v]=0;
                   9955:     FixedV[v]=0;
                   9956:   }
1.126     brouard  9957: 
1.240     brouard  9958:   for(v=1; v <=ncovcol;v++){
                   9959:     DummyV[v]=0;
                   9960:     FixedV[v]=0;
                   9961:   }
                   9962:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9963:     DummyV[v]=1;
                   9964:     FixedV[v]=0;
                   9965:   }
                   9966:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9967:     DummyV[v]=0;
                   9968:     FixedV[v]=1;
                   9969:   }
                   9970:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9971:     DummyV[v]=1;
                   9972:     FixedV[v]=1;
                   9973:   }
                   9974:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9975:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   9976:     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]);
                   9977:   }
1.126     brouard  9978: 
1.136     brouard  9979:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  9980:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   9981:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  9982:   }
1.126     brouard  9983: 
1.302     brouard  9984:     /* Is it a BOM UTF-8 Windows file? */
                   9985:   /* First data line */
                   9986:   linei=0;
                   9987:   while(fgets(line, MAXLINE, fic)) {
                   9988:     noffset=0;
                   9989:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   9990:     {
                   9991:       noffset=noffset+3;
                   9992:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   9993:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   9994:       fflush(ficlog); return 1;
                   9995:     }
                   9996:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   9997:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   9998:     {
                   9999:       noffset=noffset+2;
1.304     brouard  10000:       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);
                   10001:       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  10002:       fflush(ficlog); return 1;
                   10003:     }
                   10004:     else if( line[0] == 0 && line[1] == 0)
                   10005:     {
                   10006:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10007:        noffset=noffset+4;
1.304     brouard  10008:        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);
                   10009:        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  10010:        fflush(ficlog); return 1;
                   10011:       }
                   10012:     } else{
                   10013:       ;/*printf(" Not a BOM file\n");*/
                   10014:     }
                   10015:         /* If line starts with a # it is a comment */
                   10016:     if (line[noffset] == '#') {
                   10017:       linei=linei+1;
                   10018:       break;
                   10019:     }else{
                   10020:       break;
                   10021:     }
                   10022:   }
                   10023:   fclose(fic);
                   10024:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10025:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10026:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10027:   }
                   10028:   /* Not a Bom file */
                   10029:   
1.136     brouard  10030:   i=1;
                   10031:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10032:     linei=linei+1;
                   10033:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10034:       if(line[j] == '\t')
                   10035:        line[j] = ' ';
                   10036:     }
                   10037:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10038:       ;
                   10039:     };
                   10040:     line[j+1]=0;  /* Trims blanks at end of line */
                   10041:     if(line[0]=='#'){
                   10042:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10043:       printf("Comment line\n%s\n",line);
                   10044:       continue;
                   10045:     }
                   10046:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10047:     strcpy(line, linetmp);
1.223     brouard  10048:     
                   10049:     /* Loops on waves */
                   10050:     for (j=maxwav;j>=1;j--){
                   10051:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10052:        cutv(stra, strb, line, ' '); 
                   10053:        if(strb[0]=='.') { /* Missing value */
                   10054:          lval=-1;
                   10055:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10056:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10057:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10058:            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);
                   10059:            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);
                   10060:            return 1;
                   10061:          }
                   10062:        }else{
                   10063:          errno=0;
                   10064:          /* what_kind_of_number(strb); */
                   10065:          dval=strtod(strb,&endptr); 
                   10066:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10067:          /* if(strb != endptr && *endptr == '\0') */
                   10068:          /*    dval=dlval; */
                   10069:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10070:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10071:            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);
                   10072:            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);
                   10073:            return 1;
                   10074:          }
                   10075:          cotqvar[j][iv][i]=dval; 
                   10076:          cotvar[j][ntv+iv][i]=dval; 
                   10077:        }
                   10078:        strcpy(line,stra);
1.223     brouard  10079:       }/* end loop ntqv */
1.225     brouard  10080:       
1.223     brouard  10081:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10082:        cutv(stra, strb, line, ' '); 
                   10083:        if(strb[0]=='.') { /* Missing value */
                   10084:          lval=-1;
                   10085:        }else{
                   10086:          errno=0;
                   10087:          lval=strtol(strb,&endptr,10); 
                   10088:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10089:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10090:            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);
                   10091:            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);
                   10092:            return 1;
                   10093:          }
                   10094:        }
                   10095:        if(lval <-1 || lval >1){
                   10096:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10097:  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  10098:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10099:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10100:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10101:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10102:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10103:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10104:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10105:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10106:  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  10107:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10108:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10109:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10110:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10111:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10112:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10113:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10114:          return 1;
                   10115:        }
                   10116:        cotvar[j][iv][i]=(double)(lval);
                   10117:        strcpy(line,stra);
1.223     brouard  10118:       }/* end loop ntv */
1.225     brouard  10119:       
1.223     brouard  10120:       /* Statuses  at wave */
1.137     brouard  10121:       cutv(stra, strb, line, ' '); 
1.223     brouard  10122:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10123:        lval=-1;
1.136     brouard  10124:       }else{
1.238     brouard  10125:        errno=0;
                   10126:        lval=strtol(strb,&endptr,10); 
                   10127:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10128:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10129:          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);
                   10130:          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);
                   10131:          return 1;
                   10132:        }
1.136     brouard  10133:       }
1.225     brouard  10134:       
1.136     brouard  10135:       s[j][i]=lval;
1.225     brouard  10136:       
1.223     brouard  10137:       /* Date of Interview */
1.136     brouard  10138:       strcpy(line,stra);
                   10139:       cutv(stra, strb,line,' ');
1.169     brouard  10140:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10141:       }
1.169     brouard  10142:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10143:        month=99;
                   10144:        year=9999;
1.136     brouard  10145:       }else{
1.225     brouard  10146:        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);
                   10147:        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);
                   10148:        return 1;
1.136     brouard  10149:       }
                   10150:       anint[j][i]= (double) year; 
1.302     brouard  10151:       mint[j][i]= (double)month;
                   10152:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10153:       /*       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]); */
                   10154:       /*       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]); */
                   10155:       /* } */
1.136     brouard  10156:       strcpy(line,stra);
1.223     brouard  10157:     } /* End loop on waves */
1.225     brouard  10158:     
1.223     brouard  10159:     /* Date of death */
1.136     brouard  10160:     cutv(stra, strb,line,' '); 
1.169     brouard  10161:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10162:     }
1.169     brouard  10163:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10164:       month=99;
                   10165:       year=9999;
                   10166:     }else{
1.141     brouard  10167:       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  10168:       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);
                   10169:       return 1;
1.136     brouard  10170:     }
                   10171:     andc[i]=(double) year; 
                   10172:     moisdc[i]=(double) month; 
                   10173:     strcpy(line,stra);
                   10174:     
1.223     brouard  10175:     /* Date of birth */
1.136     brouard  10176:     cutv(stra, strb,line,' '); 
1.169     brouard  10177:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10178:     }
1.169     brouard  10179:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10180:       month=99;
                   10181:       year=9999;
                   10182:     }else{
1.141     brouard  10183:       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);
                   10184:       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  10185:       return 1;
1.136     brouard  10186:     }
                   10187:     if (year==9999) {
1.141     brouard  10188:       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);
                   10189:       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  10190:       return 1;
                   10191:       
1.136     brouard  10192:     }
                   10193:     annais[i]=(double)(year);
1.302     brouard  10194:     moisnais[i]=(double)(month);
                   10195:     for (j=1;j<=maxwav;j++){
                   10196:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10197:        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]);
                   10198:        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]);
                   10199:       }
                   10200:     }
                   10201: 
1.136     brouard  10202:     strcpy(line,stra);
1.225     brouard  10203:     
1.223     brouard  10204:     /* Sample weight */
1.136     brouard  10205:     cutv(stra, strb,line,' '); 
                   10206:     errno=0;
                   10207:     dval=strtod(strb,&endptr); 
                   10208:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10209:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10210:       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  10211:       fflush(ficlog);
                   10212:       return 1;
                   10213:     }
                   10214:     weight[i]=dval; 
                   10215:     strcpy(line,stra);
1.225     brouard  10216:     
1.223     brouard  10217:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10218:       cutv(stra, strb, line, ' '); 
                   10219:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10220:        lval=-1;
1.311     brouard  10221:        coqvar[iv][i]=NAN; 
                   10222:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10223:       }else{
1.225     brouard  10224:        errno=0;
                   10225:        /* what_kind_of_number(strb); */
                   10226:        dval=strtod(strb,&endptr);
                   10227:        /* if(strb != endptr && *endptr == '\0') */
                   10228:        /*   dval=dlval; */
                   10229:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10230:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10231:          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);
                   10232:          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);
                   10233:          return 1;
                   10234:        }
                   10235:        coqvar[iv][i]=dval; 
1.226     brouard  10236:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10237:       }
                   10238:       strcpy(line,stra);
                   10239:     }/* end loop nqv */
1.136     brouard  10240:     
1.223     brouard  10241:     /* Covariate values */
1.136     brouard  10242:     for (j=ncovcol;j>=1;j--){
                   10243:       cutv(stra, strb,line,' '); 
1.223     brouard  10244:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10245:        lval=-1;
1.136     brouard  10246:       }else{
1.225     brouard  10247:        errno=0;
                   10248:        lval=strtol(strb,&endptr,10); 
                   10249:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10250:          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);
                   10251:          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);
                   10252:          return 1;
                   10253:        }
1.136     brouard  10254:       }
                   10255:       if(lval <-1 || lval >1){
1.225     brouard  10256:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10257:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10258:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10259:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10260:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10261:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10262:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10263:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10264:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10265:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10266:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10267:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10268:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10269:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10270:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10271:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10272:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10273:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10274:        return 1;
1.136     brouard  10275:       }
                   10276:       covar[j][i]=(double)(lval);
                   10277:       strcpy(line,stra);
                   10278:     }  
                   10279:     lstra=strlen(stra);
1.225     brouard  10280:     
1.136     brouard  10281:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10282:       stratrunc = &(stra[lstra-9]);
                   10283:       num[i]=atol(stratrunc);
                   10284:     }
                   10285:     else
                   10286:       num[i]=atol(stra);
                   10287:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10288:       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;}*/
                   10289:     
                   10290:     i=i+1;
                   10291:   } /* End loop reading  data */
1.225     brouard  10292:   
1.136     brouard  10293:   *imax=i-1; /* Number of individuals */
                   10294:   fclose(fic);
1.225     brouard  10295:   
1.136     brouard  10296:   return (0);
1.164     brouard  10297:   /* endread: */
1.225     brouard  10298:   printf("Exiting readdata: ");
                   10299:   fclose(fic);
                   10300:   return (1);
1.223     brouard  10301: }
1.126     brouard  10302: 
1.234     brouard  10303: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10304:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10305:   while (*p2 == ' ')
1.234     brouard  10306:     p2++; 
                   10307:   /* while ((*p1++ = *p2++) !=0) */
                   10308:   /*   ; */
                   10309:   /* do */
                   10310:   /*   while (*p2 == ' ') */
                   10311:   /*     p2++; */
                   10312:   /* while (*p1++ == *p2++); */
                   10313:   *stri=p2; 
1.145     brouard  10314: }
                   10315: 
1.330     brouard  10316: int decoderesult( char resultline[], int nres)
1.230     brouard  10317: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10318: {
1.235     brouard  10319:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10320:   char resultsav[MAXLINE];
1.330     brouard  10321:   /* int resultmodel[MAXLINE]; */
1.334   ! brouard  10322:   /* int modelresult[MAXLINE]; */
1.230     brouard  10323:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10324: 
1.234     brouard  10325:   removefirstspace(&resultline);
1.332     brouard  10326:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10327: 
1.332     brouard  10328:   strcpy(resultsav,resultline);
                   10329:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10330:   if (strlen(resultsav) >1){
1.334   ! brouard  10331:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10332:   }
1.253     brouard  10333:   if(j == 0){ /* Resultline but no = */
                   10334:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10335:     return (0);
                   10336:   }
1.234     brouard  10337:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334   ! brouard  10338:     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);
        !          10339:     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  10340:     /* return 1;*/
1.234     brouard  10341:   }
1.334   ! brouard  10342:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10343:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10344:       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  10345:       /* 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  10346:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10347:       /* If a blank, then strc="V4=" and strd='\0' */
                   10348:       if(strc[0]=='\0'){
                   10349:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10350:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10351:        return 1;
                   10352:       }
1.234     brouard  10353:     }else
                   10354:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10355:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10356:     
1.230     brouard  10357:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10358:     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  10359:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10360:     /* cptcovsel++;     */
                   10361:     if (nbocc(stra,'=') >0)
                   10362:       strcpy(resultsav,stra); /* and analyzes it */
                   10363:   }
1.235     brouard  10364:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10365:   /* 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  10366:   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  10367:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10368:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10369:       match=0;
1.318     brouard  10370:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10371:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334   ! brouard  10372:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10373:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10374:          break;
                   10375:        }
                   10376:       }
                   10377:       if(match == 0){
1.332     brouard  10378:        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]);
                   10379:        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  10380:        return 1;
1.234     brouard  10381:       }
1.332     brouard  10382:     }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*/
                   10383:       /* We feed resultmodel[k1]=k2; */
                   10384:       match=0;
                   10385:       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 */
                   10386:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334   ! brouard  10387:          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  10388:          resultmodel[nres][k1]=k2; /* Added here */
                   10389:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10390:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10391:          break;
                   10392:        }
                   10393:       }
                   10394:       if(match == 0){
                   10395:        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  10396:        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  10397:       return 1;
                   10398:       }
                   10399:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10400:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10401:       match=0;
                   10402:       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]);
                   10403:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10404:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10405:          /* modelresult[k2]=k1; */
                   10406:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10407:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10408:        }
                   10409:       }
                   10410:       if(match == 0){
                   10411:        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  10412:        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  10413:        return 1;
                   10414:       }
                   10415:       match=0;
                   10416:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10417:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10418:          /* modelresult[k2]=k1;*/
                   10419:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10420:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10421:          break;
                   10422:        }
                   10423:       }
                   10424:       if(match == 0){
                   10425:        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  10426:        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  10427:        return 1;
                   10428:       }
                   10429:     }/* End of testing */
1.333     brouard  10430:   }/* End loop cptcovt */
1.235     brouard  10431:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10432:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334   ! brouard  10433:   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)
        !          10434:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10435:     match=0;
1.318     brouard  10436:     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  10437:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10438:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10439:          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  10440:          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  10441:          ++match;
                   10442:        }
                   10443:       }
                   10444:     }
                   10445:     if(match == 0){
1.332     brouard  10446:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
                   10447:       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  10448:       return 1;
1.234     brouard  10449:     }else if(match > 1){
                   10450:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10451:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10452:       return 1;
1.234     brouard  10453:     }
                   10454:   }
1.334   ! brouard  10455:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10456:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10457:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10458:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10459:   /* 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*/
                   10460:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10461:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10462:   /*    1 0 0 0 */
                   10463:   /*    2 1 0 0 */
                   10464:   /*    3 0 1 0 */ 
1.330     brouard  10465:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10466:   /*    5 0 0 1 */
1.330     brouard  10467:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10468:   /*    7 0 1 1 */
                   10469:   /*    8 1 1 1 */
1.237     brouard  10470:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10471:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10472:   /* V5*age V5 known which value for nres?  */
                   10473:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334   ! brouard  10474:   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.
        !          10475:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10476:     /* k counting number of combination of single dummies in the equation model */
                   10477:     /* k4 counting single dummies in the equation model */
                   10478:     /* k4q counting single quantitatives in the equation model */
1.334   ! brouard  10479:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
        !          10480:        /* 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  10481:       /* 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  10482:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10483:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10484:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10485:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10486:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10487:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334   ! brouard  10488:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10489:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10490:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10491:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10492:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10493:       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  10494:       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  10495:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10496:       /* Tinvresult[nres][4]=1 */
1.334   ! brouard  10497:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
        !          10498:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
        !          10499:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
        !          10500:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10501:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334   ! brouard  10502:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10503:       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  10504:       k4++;;
1.331     brouard  10505:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10506:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10507:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10508:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10509:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10510:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10511:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334   ! brouard  10512:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
        !          10513:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
        !          10514:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
        !          10515:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
        !          10516:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
        !          10517:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10518:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10519:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10520:       precov[nres][k1]=Tvalsel[k3q];
                   10521:       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  10522:       k4q++;;
1.331     brouard  10523:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10524:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10525:       /* Wrong we want the value of variable name Tvar[k1] */
                   10526:       
                   10527:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10528:       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  10529:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10530:       precov[nres][k1]=Tvalsel[k3];
                   10531:       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  10532:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10533:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10534:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334   ! brouard  10535:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10536:       precov[nres][k1]=Tvalsel[k3q];
1.334   ! brouard  10537:       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  10538:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10539:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10540:       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  10541:     }else{
1.332     brouard  10542:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10543:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10544:     }
                   10545:   }
1.234     brouard  10546:   
1.334   ! brouard  10547:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10548:   return (0);
                   10549: }
1.235     brouard  10550: 
1.230     brouard  10551: int decodemodel( char model[], int lastobs)
                   10552:  /**< This routine decodes the model and returns:
1.224     brouard  10553:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10554:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10555:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10556:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10557:        * - cptcovage number of covariates with age*products =2
                   10558:        * - cptcovs number of simple covariates
                   10559:        * - 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
                   10560:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10561:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10562:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10563:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10564:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10565:        */
1.319     brouard  10566: /* 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  10567: {
1.238     brouard  10568:   int i, j, k, ks, v;
1.227     brouard  10569:   int  j1, k1, k2, k3, k4;
1.136     brouard  10570:   char modelsav[80];
1.145     brouard  10571:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10572:   char *strpt;
1.136     brouard  10573: 
1.145     brouard  10574:   /*removespace(model);*/
1.136     brouard  10575:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10576:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10577:     if (strstr(model,"AGE") !=0){
1.192     brouard  10578:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10579:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10580:       return 1;
                   10581:     }
1.141     brouard  10582:     if (strstr(model,"v") !=0){
                   10583:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10584:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10585:       return 1;
                   10586:     }
1.187     brouard  10587:     strcpy(modelsav,model); 
                   10588:     if ((strpt=strstr(model,"age*age")) !=0){
                   10589:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10590:       if(strpt != model){
1.234     brouard  10591:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10592:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10593:  corresponding column of parameters.\n",model);
1.234     brouard  10594:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10595:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10596:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10597:        return 1;
1.225     brouard  10598:       }
1.187     brouard  10599:       nagesqr=1;
                   10600:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10601:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10602:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10603:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10604:       else 
1.234     brouard  10605:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10606:     }else
                   10607:       nagesqr=0;
                   10608:     if (strlen(modelsav) >1){
                   10609:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10610:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10611:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10612:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10613:                     * cst, age and age*age 
                   10614:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10615:       /* including age products which are counted in cptcovage.
                   10616:        * but the covariates which are products must be treated 
                   10617:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10618:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10619:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10620:       
                   10621:       
1.187     brouard  10622:       /*   Design
                   10623:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10624:        *  <          ncovcol=8                >
                   10625:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10626:        *   k=  1    2      3       4     5       6      7        8
                   10627:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10628:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10629:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10630:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10631:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10632:        *  Tage[++cptcovage]=k
                   10633:        *       if products, new covar are created after ncovcol with k1
                   10634:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10635:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10636:        *  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
                   10637:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10638:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10639:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10640:        *  <          ncovcol=8                >
                   10641:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10642:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10643:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10644:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10645:        * p Tprod[1]@2={                         6, 5}
                   10646:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10647:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10648:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10649:        *How to reorganize? Tvars(orted)
1.187     brouard  10650:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10651:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10652:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10653:        * Struct []
                   10654:        */
1.225     brouard  10655:       
1.187     brouard  10656:       /* This loop fills the array Tvar from the string 'model'.*/
                   10657:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10658:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10659:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10660:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10661:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10662:       /*       k=1 Tvar[1]=2 (from V2) */
                   10663:       /*       k=5 Tvar[5] */
                   10664:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10665:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10666:       /*       } */
1.198     brouard  10667:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10668:       /*
                   10669:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10670:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10671:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10672:       }
1.187     brouard  10673:       cptcovage=0;
1.319     brouard  10674:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10675:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10676:                                         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" */
                   10677:        if (nbocc(modelsav,'+')==0)
                   10678:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10679:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10680:        /*scanf("%d",i);*/
1.319     brouard  10681:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10682:          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  10683:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10684:            /* covar is not filled and then is empty */
                   10685:            cptcovprod--;
                   10686:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10687:            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  10688:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10689:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10690:            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  10691:            /*printf("stre=%s ", stre);*/
                   10692:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10693:            cptcovprod--;
                   10694:            cutl(stre,strb,strc,'V');
                   10695:            Tvar[k]=atoi(stre);
                   10696:            Typevar[k]=1;  /* 1 for age product */
                   10697:            cptcovage++;
                   10698:            Tage[cptcovage]=k;
                   10699:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10700:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10701:            cptcovn++;
                   10702:            cptcovprodnoage++;k1++;
                   10703:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10704:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10705:                                                because this model-covariate is a construction we invent a new column
                   10706:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.319     brouard  10707:                                                If already ncovcol=4 and model=V2 + V1 +V1*V4 +age*V3 +V3*V2
                   10708:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10709:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.234     brouard  10710:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10711:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10712:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10713:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10714:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10715:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10716:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10717:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10718:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10719:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10720:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10721:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10722:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10723:            for (i=1; i<=lastobs;i++){
                   10724:              /* Computes the new covariate which is a product of
                   10725:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10726:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10727:            }
                   10728:          } /* End age is not in the model */
                   10729:        } /* End if model includes a product */
1.319     brouard  10730:        else { /* not a product */
1.234     brouard  10731:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10732:          /*  scanf("%d",i);*/
                   10733:          cutl(strd,strc,strb,'V');
                   10734:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10735:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10736:          Tvar[k]=atoi(strd);
                   10737:          Typevar[k]=0;  /* 0 for simple covariates */
                   10738:        }
                   10739:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10740:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10741:                                  scanf("%d",i);*/
1.187     brouard  10742:       } /* end of loop + on total covariates */
                   10743:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10744:   } /* end if strlen(model == 0) */
1.136     brouard  10745:   
                   10746:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10747:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10748:   
1.136     brouard  10749:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10750:      printf("cptcovprod=%d ", cptcovprod);
                   10751:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10752:      scanf("%d ",i);*/
                   10753: 
                   10754: 
1.230     brouard  10755: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10756:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10757: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10758:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10759:    k =           1    2   3     4       5       6      7      8        9
                   10760:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10761:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10762:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10763:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10764:          Tmodelind[combination of covar]=k;
1.225     brouard  10765: */  
                   10766: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10767:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10768:   /* 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  10769:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10770:   printf("Model=1+age+%s\n\
1.227     brouard  10771: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10772: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10773: 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  10774:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10775: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10776: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10777: 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  10778:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10779:   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 */
                   10780:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10781:       Fixed[k]= 0;
                   10782:       Dummy[k]= 0;
1.225     brouard  10783:       ncoveff++;
1.232     brouard  10784:       ncovf++;
1.234     brouard  10785:       nsd++;
                   10786:       modell[k].maintype= FTYPE;
                   10787:       TvarsD[nsd]=Tvar[k];
                   10788:       TvarsDind[nsd]=k;
1.330     brouard  10789:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10790:       TvarF[ncovf]=Tvar[k];
                   10791:       TvarFind[ncovf]=k;
                   10792:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10793:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10794:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10795:       Fixed[k]= 0;
                   10796:       Dummy[k]= 0;
                   10797:       ncoveff++;
                   10798:       ncovf++;
                   10799:       modell[k].maintype= FTYPE;
                   10800:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10801:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10802:       TvarFind[ncovf]=k;
1.230     brouard  10803:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10804:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10805:     }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  10806:       Fixed[k]= 0;
                   10807:       Dummy[k]= 1;
1.230     brouard  10808:       nqfveff++;
1.234     brouard  10809:       modell[k].maintype= FTYPE;
                   10810:       modell[k].subtype= FQ;
                   10811:       nsq++;
1.334   ! brouard  10812:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
        !          10813:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  10814:       ncovf++;
1.234     brouard  10815:       TvarF[ncovf]=Tvar[k];
                   10816:       TvarFind[ncovf]=k;
1.231     brouard  10817:       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  10818:       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  10819:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10820:       Fixed[k]= 1;
                   10821:       Dummy[k]= 0;
1.225     brouard  10822:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10823:       modell[k].maintype= VTYPE;
                   10824:       modell[k].subtype= VD;
                   10825:       nsd++;
                   10826:       TvarsD[nsd]=Tvar[k];
                   10827:       TvarsDind[nsd]=k;
1.330     brouard  10828:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10829:       ncovv++; /* Only simple time varying variables */
                   10830:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10831:       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  10832:       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 */
                   10833:       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  10834:       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);
                   10835:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10836:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10837:       Fixed[k]= 1;
                   10838:       Dummy[k]= 1;
                   10839:       nqtveff++;
                   10840:       modell[k].maintype= VTYPE;
                   10841:       modell[k].subtype= VQ;
                   10842:       ncovv++; /* Only simple time varying variables */
                   10843:       nsq++;
1.334   ! brouard  10844:       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) */
        !          10845:       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  10846:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10847:       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  10848:       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 */
                   10849:       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  10850:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10851:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10852:       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  10853:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10854:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10855:       ncova++;
                   10856:       TvarA[ncova]=Tvar[k];
                   10857:       TvarAind[ncova]=k;
1.231     brouard  10858:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10859:        Fixed[k]= 2;
                   10860:        Dummy[k]= 2;
                   10861:        modell[k].maintype= ATYPE;
                   10862:        modell[k].subtype= APFD;
                   10863:        /* ncoveff++; */
1.227     brouard  10864:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10865:        Fixed[k]= 2;
                   10866:        Dummy[k]= 3;
                   10867:        modell[k].maintype= ATYPE;
                   10868:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10869:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10870:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10871:        Fixed[k]= 3;
                   10872:        Dummy[k]= 2;
                   10873:        modell[k].maintype= ATYPE;
                   10874:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10875:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10876:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10877:        Fixed[k]= 3;
                   10878:        Dummy[k]= 3;
                   10879:        modell[k].maintype= ATYPE;
                   10880:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10881:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10882:       }
                   10883:     }else if (Typevar[k] == 2) {  /* product without age */
                   10884:       k1=Tposprod[k];
                   10885:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10886:        if(Tvard[k1][2] <=ncovcol){
                   10887:          Fixed[k]= 1;
                   10888:          Dummy[k]= 0;
                   10889:          modell[k].maintype= FTYPE;
                   10890:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10891:          ncovf++; /* Fixed variables without age */
                   10892:          TvarF[ncovf]=Tvar[k];
                   10893:          TvarFind[ncovf]=k;
                   10894:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10895:          Fixed[k]= 0;  /* or 2 ?*/
                   10896:          Dummy[k]= 1;
                   10897:          modell[k].maintype= FTYPE;
                   10898:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10899:          ncovf++; /* Varying variables without age */
                   10900:          TvarF[ncovf]=Tvar[k];
                   10901:          TvarFind[ncovf]=k;
                   10902:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10903:          Fixed[k]= 1;
                   10904:          Dummy[k]= 0;
                   10905:          modell[k].maintype= VTYPE;
                   10906:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10907:          ncovv++; /* Varying variables without age */
                   10908:          TvarV[ncovv]=Tvar[k];
                   10909:          TvarVind[ncovv]=k;
                   10910:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10911:          Fixed[k]= 1;
                   10912:          Dummy[k]= 1;
                   10913:          modell[k].maintype= VTYPE;
                   10914:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10915:          ncovv++; /* Varying variables without age */
                   10916:          TvarV[ncovv]=Tvar[k];
                   10917:          TvarVind[ncovv]=k;
                   10918:        }
1.227     brouard  10919:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10920:        if(Tvard[k1][2] <=ncovcol){
                   10921:          Fixed[k]= 0;  /* or 2 ?*/
                   10922:          Dummy[k]= 1;
                   10923:          modell[k].maintype= FTYPE;
                   10924:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10925:          ncovf++; /* Fixed variables without age */
                   10926:          TvarF[ncovf]=Tvar[k];
                   10927:          TvarFind[ncovf]=k;
                   10928:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10929:          Fixed[k]= 1;
                   10930:          Dummy[k]= 1;
                   10931:          modell[k].maintype= VTYPE;
                   10932:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10933:          ncovv++; /* Varying variables without age */
                   10934:          TvarV[ncovv]=Tvar[k];
                   10935:          TvarVind[ncovv]=k;
                   10936:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10937:          Fixed[k]= 1;
                   10938:          Dummy[k]= 1;
                   10939:          modell[k].maintype= VTYPE;
                   10940:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10941:          ncovv++; /* Varying variables without age */
                   10942:          TvarV[ncovv]=Tvar[k];
                   10943:          TvarVind[ncovv]=k;
                   10944:          ncovv++; /* Varying variables without age */
                   10945:          TvarV[ncovv]=Tvar[k];
                   10946:          TvarVind[ncovv]=k;
                   10947:        }
1.227     brouard  10948:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10949:        if(Tvard[k1][2] <=ncovcol){
                   10950:          Fixed[k]= 1;
                   10951:          Dummy[k]= 1;
                   10952:          modell[k].maintype= VTYPE;
                   10953:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10954:          ncovv++; /* Varying variables without age */
                   10955:          TvarV[ncovv]=Tvar[k];
                   10956:          TvarVind[ncovv]=k;
                   10957:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10958:          Fixed[k]= 1;
                   10959:          Dummy[k]= 1;
                   10960:          modell[k].maintype= VTYPE;
                   10961:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10962:          ncovv++; /* Varying variables without age */
                   10963:          TvarV[ncovv]=Tvar[k];
                   10964:          TvarVind[ncovv]=k;
                   10965:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10966:          Fixed[k]= 1;
                   10967:          Dummy[k]= 0;
                   10968:          modell[k].maintype= VTYPE;
                   10969:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   10970:          ncovv++; /* Varying variables without age */
                   10971:          TvarV[ncovv]=Tvar[k];
                   10972:          TvarVind[ncovv]=k;
                   10973:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10974:          Fixed[k]= 1;
                   10975:          Dummy[k]= 1;
                   10976:          modell[k].maintype= VTYPE;
                   10977:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   10978:          ncovv++; /* Varying variables without age */
                   10979:          TvarV[ncovv]=Tvar[k];
                   10980:          TvarVind[ncovv]=k;
                   10981:        }
1.227     brouard  10982:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10983:        if(Tvard[k1][2] <=ncovcol){
                   10984:          Fixed[k]= 1;
                   10985:          Dummy[k]= 1;
                   10986:          modell[k].maintype= VTYPE;
                   10987:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   10988:          ncovv++; /* Varying variables without age */
                   10989:          TvarV[ncovv]=Tvar[k];
                   10990:          TvarVind[ncovv]=k;
                   10991:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10992:          Fixed[k]= 1;
                   10993:          Dummy[k]= 1;
                   10994:          modell[k].maintype= VTYPE;
                   10995:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   10996:          ncovv++; /* Varying variables without age */
                   10997:          TvarV[ncovv]=Tvar[k];
                   10998:          TvarVind[ncovv]=k;
                   10999:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11000:          Fixed[k]= 1;
                   11001:          Dummy[k]= 1;
                   11002:          modell[k].maintype= VTYPE;
                   11003:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11004:          ncovv++; /* Varying variables without age */
                   11005:          TvarV[ncovv]=Tvar[k];
                   11006:          TvarVind[ncovv]=k;
                   11007:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11008:          Fixed[k]= 1;
                   11009:          Dummy[k]= 1;
                   11010:          modell[k].maintype= VTYPE;
                   11011:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11012:          ncovv++; /* Varying variables without age */
                   11013:          TvarV[ncovv]=Tvar[k];
                   11014:          TvarVind[ncovv]=k;
                   11015:        }
1.227     brouard  11016:       }else{
1.240     brouard  11017:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11018:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11019:       } /*end k1*/
1.225     brouard  11020:     }else{
1.226     brouard  11021:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11022:       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  11023:     }
1.227     brouard  11024:     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  11025:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11026:     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]);
                   11027:   }
                   11028:   /* Searching for doublons in the model */
                   11029:   for(k1=1; k1<= cptcovt;k1++){
                   11030:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11031:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11032:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11033:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11034:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  11035:            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]);
                   11036:            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  11037:            return(1);
                   11038:          }
                   11039:        }else if (Typevar[k1] ==2){
                   11040:          k3=Tposprod[k1];
                   11041:          k4=Tposprod[k2];
                   11042:          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])) ){
                   11043:            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]]);
                   11044:            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);
                   11045:            return(1);
                   11046:          }
                   11047:        }
1.227     brouard  11048:       }
                   11049:     }
1.225     brouard  11050:   }
                   11051:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11052:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11053:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11054:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11055:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11056:   /*endread:*/
1.225     brouard  11057:   printf("Exiting decodemodel: ");
                   11058:   return (1);
1.136     brouard  11059: }
                   11060: 
1.169     brouard  11061: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11062: {/* Check ages at death */
1.136     brouard  11063:   int i, m;
1.218     brouard  11064:   int firstone=0;
                   11065:   
1.136     brouard  11066:   for (i=1; i<=imx; i++) {
                   11067:     for(m=2; (m<= maxwav); m++) {
                   11068:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11069:        anint[m][i]=9999;
1.216     brouard  11070:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11071:          s[m][i]=-1;
1.136     brouard  11072:       }
                   11073:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11074:        *nberr = *nberr + 1;
1.218     brouard  11075:        if(firstone == 0){
                   11076:          firstone=1;
1.260     brouard  11077:        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  11078:        }
1.262     brouard  11079:        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  11080:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11081:       }
                   11082:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11083:        (*nberr)++;
1.259     brouard  11084:        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  11085:        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  11086:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11087:       }
                   11088:     }
                   11089:   }
                   11090: 
                   11091:   for (i=1; i<=imx; i++)  {
                   11092:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11093:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11094:       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  11095:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11096:          if(agedc[i]>0){
                   11097:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11098:              agev[m][i]=agedc[i];
1.214     brouard  11099:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11100:            }else {
1.136     brouard  11101:              if ((int)andc[i]!=9999){
                   11102:                nbwarn++;
                   11103:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11104:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11105:                agev[m][i]=-1;
                   11106:              }
                   11107:            }
1.169     brouard  11108:          } /* agedc > 0 */
1.214     brouard  11109:        } /* end if */
1.136     brouard  11110:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11111:                                 years but with the precision of a month */
                   11112:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11113:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11114:            agev[m][i]=1;
                   11115:          else if(agev[m][i] < *agemin){ 
                   11116:            *agemin=agev[m][i];
                   11117:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11118:          }
                   11119:          else if(agev[m][i] >*agemax){
                   11120:            *agemax=agev[m][i];
1.156     brouard  11121:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11122:          }
                   11123:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11124:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11125:        } /* en if 9*/
1.136     brouard  11126:        else { /* =9 */
1.214     brouard  11127:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11128:          agev[m][i]=1;
                   11129:          s[m][i]=-1;
                   11130:        }
                   11131:       }
1.214     brouard  11132:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11133:        agev[m][i]=1;
1.214     brouard  11134:       else{
                   11135:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11136:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11137:        agev[m][i]=0;
                   11138:       }
                   11139:     } /* End for lastpass */
                   11140:   }
1.136     brouard  11141:     
                   11142:   for (i=1; i<=imx; i++)  {
                   11143:     for(m=firstpass; (m<=lastpass); m++){
                   11144:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11145:        (*nberr)++;
1.136     brouard  11146:        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);     
                   11147:        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);     
                   11148:        return 1;
                   11149:       }
                   11150:     }
                   11151:   }
                   11152: 
                   11153:   /*for (i=1; i<=imx; i++){
                   11154:   for (m=firstpass; (m<lastpass); m++){
                   11155:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11156: }
                   11157: 
                   11158: }*/
                   11159: 
                   11160: 
1.139     brouard  11161:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11162:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11163: 
                   11164:   return (0);
1.164     brouard  11165:  /* endread:*/
1.136     brouard  11166:     printf("Exiting calandcheckages: ");
                   11167:     return (1);
                   11168: }
                   11169: 
1.172     brouard  11170: #if defined(_MSC_VER)
                   11171: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11172: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11173: //#include "stdafx.h"
                   11174: //#include <stdio.h>
                   11175: //#include <tchar.h>
                   11176: //#include <windows.h>
                   11177: //#include <iostream>
                   11178: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11179: 
                   11180: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11181: 
                   11182: BOOL IsWow64()
                   11183: {
                   11184:        BOOL bIsWow64 = FALSE;
                   11185: 
                   11186:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11187:        //  (HANDLE, PBOOL);
                   11188: 
                   11189:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11190: 
                   11191:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11192:        const char funcName[] = "IsWow64Process";
                   11193:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11194:                GetProcAddress(module, funcName);
                   11195: 
                   11196:        if (NULL != fnIsWow64Process)
                   11197:        {
                   11198:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11199:                        &bIsWow64))
                   11200:                        //throw std::exception("Unknown error");
                   11201:                        printf("Unknown error\n");
                   11202:        }
                   11203:        return bIsWow64 != FALSE;
                   11204: }
                   11205: #endif
1.177     brouard  11206: 
1.191     brouard  11207: void syscompilerinfo(int logged)
1.292     brouard  11208: {
                   11209: #include <stdint.h>
                   11210: 
                   11211:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11212:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11213:    /* /GS /W3 /Gy
                   11214:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11215:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11216:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11217:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11218:    */ 
                   11219:    /* 64 bits */
1.185     brouard  11220:    /*
                   11221:      /GS /W3 /Gy
                   11222:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11223:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11224:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11225:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11226:    /* Optimization are useless and O3 is slower than O2 */
                   11227:    /*
                   11228:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11229:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11230:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11231:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11232:    */
1.186     brouard  11233:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11234:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11235:       /PDB:"visual studio
                   11236:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11237:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11238:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11239:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11240:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11241:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11242:       uiAccess='false'"
                   11243:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11244:       /NOLOGO /TLBID:1
                   11245:    */
1.292     brouard  11246: 
                   11247: 
1.177     brouard  11248: #if defined __INTEL_COMPILER
1.178     brouard  11249: #if defined(__GNUC__)
                   11250:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11251: #endif
1.177     brouard  11252: #elif defined(__GNUC__) 
1.179     brouard  11253: #ifndef  __APPLE__
1.174     brouard  11254: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11255: #endif
1.177     brouard  11256:    struct utsname sysInfo;
1.178     brouard  11257:    int cross = CROSS;
                   11258:    if (cross){
                   11259:           printf("Cross-");
1.191     brouard  11260:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11261:    }
1.174     brouard  11262: #endif
                   11263: 
1.191     brouard  11264:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11265: #if defined(__clang__)
1.191     brouard  11266:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11267: #endif
                   11268: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11269:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11270: #endif
                   11271: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11272:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11273: #endif
                   11274: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11275:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11276: #endif
                   11277: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11278:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11279: #endif
                   11280: #if defined(_MSC_VER)
1.191     brouard  11281:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11282: #endif
                   11283: #if defined(__PGI)
1.191     brouard  11284:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11285: #endif
                   11286: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11287:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11288: #endif
1.191     brouard  11289:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11290:    
1.167     brouard  11291: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11292: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11293:     // Windows (x64 and x86)
1.191     brouard  11294:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11295: #elif __unix__ // all unices, not all compilers
                   11296:     // Unix
1.191     brouard  11297:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11298: #elif __linux__
                   11299:     // linux
1.191     brouard  11300:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11301: #elif __APPLE__
1.174     brouard  11302:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11303:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11304: #endif
                   11305: 
                   11306: /*  __MINGW32__          */
                   11307: /*  __CYGWIN__  */
                   11308: /* __MINGW64__  */
                   11309: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11310: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11311: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11312: /* _WIN64  // Defined for applications for Win64. */
                   11313: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11314: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11315: 
1.167     brouard  11316: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11317:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11318: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11319:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11320: #else
1.191     brouard  11321:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11322: #endif
                   11323: 
1.169     brouard  11324: #if defined(__GNUC__)
                   11325: # if defined(__GNUC_PATCHLEVEL__)
                   11326: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11327:                             + __GNUC_MINOR__ * 100 \
                   11328:                             + __GNUC_PATCHLEVEL__)
                   11329: # else
                   11330: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11331:                             + __GNUC_MINOR__ * 100)
                   11332: # endif
1.174     brouard  11333:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11334:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11335: 
                   11336:    if (uname(&sysInfo) != -1) {
                   11337:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11338:         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  11339:    }
                   11340:    else
                   11341:       perror("uname() error");
1.179     brouard  11342:    //#ifndef __INTEL_COMPILER 
                   11343: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11344:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11345:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11346: #endif
1.169     brouard  11347: #endif
1.172     brouard  11348: 
1.286     brouard  11349:    //   void main ()
1.172     brouard  11350:    //   {
1.169     brouard  11351: #if defined(_MSC_VER)
1.174     brouard  11352:    if (IsWow64()){
1.191     brouard  11353:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11354:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11355:    }
                   11356:    else{
1.191     brouard  11357:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11358:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11359:    }
1.172     brouard  11360:    //     printf("\nPress Enter to continue...");
                   11361:    //     getchar();
                   11362:    //   }
                   11363: 
1.169     brouard  11364: #endif
                   11365:    
1.167     brouard  11366: 
1.219     brouard  11367: }
1.136     brouard  11368: 
1.219     brouard  11369: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11370:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11371:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11372:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11373:   /* double ftolpl = 1.e-10; */
1.180     brouard  11374:   double age, agebase, agelim;
1.203     brouard  11375:   double tot;
1.180     brouard  11376: 
1.202     brouard  11377:   strcpy(filerespl,"PL_");
                   11378:   strcat(filerespl,fileresu);
                   11379:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11380:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11381:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11382:   }
1.288     brouard  11383:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11384:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11385:   pstamp(ficrespl);
1.288     brouard  11386:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11387:   fprintf(ficrespl,"#Age ");
                   11388:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11389:   fprintf(ficrespl,"\n");
1.180     brouard  11390:   
1.219     brouard  11391:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11392: 
1.219     brouard  11393:   agebase=ageminpar;
                   11394:   agelim=agemaxpar;
1.180     brouard  11395: 
1.227     brouard  11396:   /* i1=pow(2,ncoveff); */
1.234     brouard  11397:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11398:   if (cptcovn < 1){i1=1;}
1.180     brouard  11399: 
1.238     brouard  11400:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11401:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11402:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11403:        continue;
1.235     brouard  11404: 
1.238     brouard  11405:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11406:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11407:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11408:       /* k=k+1; */
                   11409:       /* to clean */
1.332     brouard  11410:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11411:       fprintf(ficrespl,"#******");
                   11412:       printf("#******");
                   11413:       fprintf(ficlog,"#******");
                   11414:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11415:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   11416:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* Here problem for varying dummy*/
                   11417:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11418:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11419:       }
                   11420:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11421:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11422:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11423:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11424:       }
                   11425:       fprintf(ficrespl,"******\n");
                   11426:       printf("******\n");
                   11427:       fprintf(ficlog,"******\n");
                   11428:       if(invalidvarcomb[k]){
                   11429:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11430:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11431:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11432:        continue;
                   11433:       }
1.219     brouard  11434: 
1.238     brouard  11435:       fprintf(ficrespl,"#Age ");
                   11436:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11437:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11438:       }
                   11439:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11440:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11441:     
1.238     brouard  11442:       for (age=agebase; age<=agelim; age++){
                   11443:        /* for (age=agebase; age<=agebase; age++){ */
                   11444:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11445:        fprintf(ficrespl,"%.0f ",age );
                   11446:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11447:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11448:        tot=0.;
                   11449:        for(i=1; i<=nlstate;i++){
                   11450:          tot +=  prlim[i][i];
                   11451:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11452:        }
                   11453:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11454:       } /* Age */
                   11455:       /* was end of cptcod */
                   11456:     } /* cptcov */
                   11457:   } /* nres */
1.219     brouard  11458:   return 0;
1.180     brouard  11459: }
                   11460: 
1.218     brouard  11461: 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  11462:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11463:        
                   11464:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11465:    * at any age between ageminpar and agemaxpar
                   11466:         */
1.235     brouard  11467:   int i, j, k, i1, nres=0 ;
1.217     brouard  11468:   /* double ftolpl = 1.e-10; */
                   11469:   double age, agebase, agelim;
                   11470:   double tot;
1.218     brouard  11471:   /* double ***mobaverage; */
                   11472:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11473: 
                   11474:   strcpy(fileresplb,"PLB_");
                   11475:   strcat(fileresplb,fileresu);
                   11476:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11477:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11478:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11479:   }
1.288     brouard  11480:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11481:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11482:   pstamp(ficresplb);
1.288     brouard  11483:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11484:   fprintf(ficresplb,"#Age ");
                   11485:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11486:   fprintf(ficresplb,"\n");
                   11487:   
1.218     brouard  11488:   
                   11489:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11490:   
                   11491:   agebase=ageminpar;
                   11492:   agelim=agemaxpar;
                   11493:   
                   11494:   
1.227     brouard  11495:   i1=pow(2,cptcoveff);
1.218     brouard  11496:   if (cptcovn < 1){i1=1;}
1.227     brouard  11497:   
1.238     brouard  11498:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11499:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11500:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11501:        continue;
1.332     brouard  11502:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11503:       fprintf(ficresplb,"#******");
                   11504:       printf("#******");
                   11505:       fprintf(ficlog,"#******");
                   11506:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11507:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11508:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11509:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11510:       }
                   11511:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11512:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11513:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11514:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11515:       }
                   11516:       fprintf(ficresplb,"******\n");
                   11517:       printf("******\n");
                   11518:       fprintf(ficlog,"******\n");
                   11519:       if(invalidvarcomb[k]){
                   11520:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11521:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11522:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11523:        continue;
                   11524:       }
1.218     brouard  11525:     
1.238     brouard  11526:       fprintf(ficresplb,"#Age ");
                   11527:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11528:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11529:       }
                   11530:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11531:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11532:     
                   11533:     
1.238     brouard  11534:       for (age=agebase; age<=agelim; age++){
                   11535:        /* for (age=agebase; age<=agebase; age++){ */
                   11536:        if(mobilavproj > 0){
                   11537:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11538:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11539:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11540:        }else if (mobilavproj == 0){
                   11541:          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);
                   11542:          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);
                   11543:          exit(1);
                   11544:        }else{
                   11545:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11546:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11547:          /* printf("TOTOT\n"); */
                   11548:           /* exit(1); */
1.238     brouard  11549:        }
                   11550:        fprintf(ficresplb,"%.0f ",age );
                   11551:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11552:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11553:        tot=0.;
                   11554:        for(i=1; i<=nlstate;i++){
                   11555:          tot +=  bprlim[i][i];
                   11556:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11557:        }
                   11558:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11559:       } /* Age */
                   11560:       /* was end of cptcod */
1.255     brouard  11561:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11562:     } /* end of any combination */
                   11563:   } /* end of nres */  
1.218     brouard  11564:   /* hBijx(p, bage, fage); */
                   11565:   /* fclose(ficrespijb); */
                   11566:   
                   11567:   return 0;
1.217     brouard  11568: }
1.218     brouard  11569:  
1.180     brouard  11570: int hPijx(double *p, int bage, int fage){
                   11571:     /*------------- h Pij x at various ages ------------*/
                   11572: 
                   11573:   int stepsize;
                   11574:   int agelim;
                   11575:   int hstepm;
                   11576:   int nhstepm;
1.235     brouard  11577:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11578: 
                   11579:   double agedeb;
                   11580:   double ***p3mat;
                   11581: 
1.201     brouard  11582:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11583:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11584:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11585:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11586:     }
                   11587:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11588:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11589:   
                   11590:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11591:     /*if (stepm<=24) stepsize=2;*/
                   11592: 
                   11593:     agelim=AGESUP;
                   11594:     hstepm=stepsize*YEARM; /* Every year of age */
                   11595:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11596:                
1.180     brouard  11597:     /* hstepm=1;   aff par mois*/
                   11598:     pstamp(ficrespij);
                   11599:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11600:     i1= pow(2,cptcoveff);
1.218     brouard  11601:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11602:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11603:                /*      k=k+1;  */
1.235     brouard  11604:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11605:     for(k=1; k<=i1;k++){
1.253     brouard  11606:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11607:        continue;
1.183     brouard  11608:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11609:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  11610:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  11611:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11612:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11613:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11614:       }
1.183     brouard  11615:       fprintf(ficrespij,"******\n");
                   11616:       
                   11617:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11618:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11619:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11620:        
                   11621:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11622:        
1.183     brouard  11623:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11624:        oldm=oldms;savm=savms;
1.235     brouard  11625:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11626:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11627:        for(i=1; i<=nlstate;i++)
                   11628:          for(j=1; j<=nlstate+ndeath;j++)
                   11629:            fprintf(ficrespij," %1d-%1d",i,j);
                   11630:        fprintf(ficrespij,"\n");
                   11631:        for (h=0; h<=nhstepm; h++){
                   11632:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11633:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11634:          for(i=1; i<=nlstate;i++)
                   11635:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11636:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11637:          fprintf(ficrespij,"\n");
                   11638:        }
1.183     brouard  11639:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11640:        fprintf(ficrespij,"\n");
                   11641:       }
1.180     brouard  11642:       /*}*/
                   11643:     }
1.218     brouard  11644:     return 0;
1.180     brouard  11645: }
1.218     brouard  11646:  
                   11647:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11648:     /*------------- h Bij x at various ages ------------*/
                   11649: 
                   11650:   int stepsize;
1.218     brouard  11651:   /* int agelim; */
                   11652:        int ageminl;
1.217     brouard  11653:   int hstepm;
                   11654:   int nhstepm;
1.238     brouard  11655:   int h, i, i1, j, k, nres;
1.218     brouard  11656:        
1.217     brouard  11657:   double agedeb;
                   11658:   double ***p3mat;
1.218     brouard  11659:        
                   11660:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11661:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11662:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11663:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11664:   }
                   11665:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11666:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11667:   
                   11668:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11669:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11670:   
1.218     brouard  11671:   /* agelim=AGESUP; */
1.289     brouard  11672:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11673:   hstepm=stepsize*YEARM; /* Every year of age */
                   11674:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11675:   
                   11676:   /* hstepm=1;   aff par mois*/
                   11677:   pstamp(ficrespijb);
1.255     brouard  11678:   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  11679:   i1= pow(2,cptcoveff);
1.218     brouard  11680:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11681:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11682:   /*   k=k+1;  */
1.238     brouard  11683:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11684:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11685:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11686:        continue;
                   11687:       fprintf(ficrespijb,"\n#****** ");
                   11688:       for(j=1;j<=cptcoveff;j++)
1.332     brouard  11689:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11690:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11691:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11692:       }
                   11693:       fprintf(ficrespijb,"******\n");
1.264     brouard  11694:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11695:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11696:        continue;
                   11697:       }
                   11698:       
                   11699:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11700:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11701:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11702:        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 */
                   11703:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11704:        
                   11705:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11706:        
1.266     brouard  11707:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11708:        /* and memory limitations if stepm is small */
                   11709: 
1.238     brouard  11710:        /* oldm=oldms;savm=savms; */
                   11711:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11712:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11713:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11714:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11715:        for(i=1; i<=nlstate;i++)
                   11716:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11717:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11718:        fprintf(ficrespijb,"\n");
1.238     brouard  11719:        for (h=0; h<=nhstepm; h++){
                   11720:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11721:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11722:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11723:          for(i=1; i<=nlstate;i++)
                   11724:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11725:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11726:          fprintf(ficrespijb,"\n");
                   11727:        }
                   11728:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11729:        fprintf(ficrespijb,"\n");
                   11730:       } /* end age deb */
                   11731:     } /* end combination */
                   11732:   } /* end nres */
1.218     brouard  11733:   return 0;
                   11734:  } /*  hBijx */
1.217     brouard  11735: 
1.180     brouard  11736: 
1.136     brouard  11737: /***********************************************/
                   11738: /**************** Main Program *****************/
                   11739: /***********************************************/
                   11740: 
                   11741: int main(int argc, char *argv[])
                   11742: {
                   11743: #ifdef GSL
                   11744:   const gsl_multimin_fminimizer_type *T;
                   11745:   size_t iteri = 0, it;
                   11746:   int rval = GSL_CONTINUE;
                   11747:   int status = GSL_SUCCESS;
                   11748:   double ssval;
                   11749: #endif
                   11750:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11751:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11752:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11753:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11754:   int jj, ll, li, lj, lk;
1.136     brouard  11755:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11756:   int num_filled;
1.136     brouard  11757:   int itimes;
                   11758:   int NDIM=2;
                   11759:   int vpopbased=0;
1.235     brouard  11760:   int nres=0;
1.258     brouard  11761:   int endishere=0;
1.277     brouard  11762:   int noffset=0;
1.274     brouard  11763:   int ncurrv=0; /* Temporary variable */
                   11764:   
1.164     brouard  11765:   char ca[32], cb[32];
1.136     brouard  11766:   /*  FILE *fichtm; *//* Html File */
                   11767:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11768:   struct stat info;
1.191     brouard  11769:   double agedeb=0.;
1.194     brouard  11770: 
                   11771:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11772:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11773: 
1.165     brouard  11774:   double fret;
1.191     brouard  11775:   double dum=0.; /* Dummy variable */
1.136     brouard  11776:   double ***p3mat;
1.218     brouard  11777:   /* double ***mobaverage; */
1.319     brouard  11778:   double wald;
1.164     brouard  11779: 
                   11780:   char line[MAXLINE];
1.197     brouard  11781:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11782: 
1.234     brouard  11783:   char  modeltemp[MAXLINE];
1.332     brouard  11784:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11785:   
1.136     brouard  11786:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11787:   char *tok, *val; /* pathtot */
1.334   ! brouard  11788:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  11789:   int c,  h , cpt, c2;
1.191     brouard  11790:   int jl=0;
                   11791:   int i1, j1, jk, stepsize=0;
1.194     brouard  11792:   int count=0;
                   11793: 
1.164     brouard  11794:   int *tab; 
1.136     brouard  11795:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11796:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11797:   /* double anprojf, mprojf, jprojf; */
                   11798:   /* double jintmean,mintmean,aintmean;   */
                   11799:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11800:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11801:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11802:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11803:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11804:   int mobilav=0,popforecast=0;
1.191     brouard  11805:   int hstepm=0, nhstepm=0;
1.136     brouard  11806:   int agemortsup;
                   11807:   float  sumlpop=0.;
                   11808:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11809:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11810: 
1.191     brouard  11811:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11812:   double ftolpl=FTOL;
                   11813:   double **prlim;
1.217     brouard  11814:   double **bprlim;
1.317     brouard  11815:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11816:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11817:   double ***paramstart; /* Matrix of starting parameter values */
                   11818:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11819:   double **matcov; /* Matrix of covariance */
1.203     brouard  11820:   double **hess; /* Hessian matrix */
1.136     brouard  11821:   double ***delti3; /* Scale */
                   11822:   double *delti; /* Scale */
                   11823:   double ***eij, ***vareij;
                   11824:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11825: 
1.136     brouard  11826:   double *epj, vepp;
1.164     brouard  11827: 
1.273     brouard  11828:   double dateprev1, dateprev2;
1.296     brouard  11829:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11830:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11831: 
1.217     brouard  11832: 
1.136     brouard  11833:   double **ximort;
1.145     brouard  11834:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11835:   int *dcwave;
                   11836: 
1.164     brouard  11837:   char z[1]="c";
1.136     brouard  11838: 
                   11839:   /*char  *strt;*/
                   11840:   char strtend[80];
1.126     brouard  11841: 
1.164     brouard  11842: 
1.126     brouard  11843: /*   setlocale (LC_ALL, ""); */
                   11844: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11845: /*   textdomain (PACKAGE); */
                   11846: /*   setlocale (LC_CTYPE, ""); */
                   11847: /*   setlocale (LC_MESSAGES, ""); */
                   11848: 
                   11849:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11850:   rstart_time = time(NULL);  
                   11851:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11852:   start_time = *localtime(&rstart_time);
1.126     brouard  11853:   curr_time=start_time;
1.157     brouard  11854:   /*tml = *localtime(&start_time.tm_sec);*/
                   11855:   /* strcpy(strstart,asctime(&tml)); */
                   11856:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11857: 
                   11858: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11859: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11860: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11861: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11862: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11863: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11864: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11865: /*   strt=asctime(&tmg); */
                   11866: /*   printf("Time(after) =%s",strstart);  */
                   11867: /*  (void) time (&time_value);
                   11868: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11869: *  tm = *localtime(&time_value);
                   11870: *  strstart=asctime(&tm);
                   11871: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11872: */
                   11873: 
                   11874:   nberr=0; /* Number of errors and warnings */
                   11875:   nbwarn=0;
1.184     brouard  11876: #ifdef WIN32
                   11877:   _getcwd(pathcd, size);
                   11878: #else
1.126     brouard  11879:   getcwd(pathcd, size);
1.184     brouard  11880: #endif
1.191     brouard  11881:   syscompilerinfo(0);
1.196     brouard  11882:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11883:   if(argc <=1){
                   11884:     printf("\nEnter the parameter file name: ");
1.205     brouard  11885:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11886:       printf("ERROR Empty parameter file name\n");
                   11887:       goto end;
                   11888:     }
1.126     brouard  11889:     i=strlen(pathr);
                   11890:     if(pathr[i-1]=='\n')
                   11891:       pathr[i-1]='\0';
1.156     brouard  11892:     i=strlen(pathr);
1.205     brouard  11893:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11894:       pathr[i-1]='\0';
1.205     brouard  11895:     }
                   11896:     i=strlen(pathr);
                   11897:     if( i==0 ){
                   11898:       printf("ERROR Empty parameter file name\n");
                   11899:       goto end;
                   11900:     }
                   11901:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11902:       printf("Pathr |%s|\n",pathr);
                   11903:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11904:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11905:       strcpy (pathtot, val);
                   11906:       if(pathr[0] == '\0') break; /* Dirty */
                   11907:     }
                   11908:   }
1.281     brouard  11909:   else if (argc<=2){
                   11910:     strcpy(pathtot,argv[1]);
                   11911:   }
1.126     brouard  11912:   else{
                   11913:     strcpy(pathtot,argv[1]);
1.281     brouard  11914:     strcpy(z,argv[2]);
                   11915:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11916:   }
                   11917:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11918:   /*cygwin_split_path(pathtot,path,optionfile);
                   11919:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11920:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11921: 
                   11922:   /* Split argv[0], imach program to get pathimach */
                   11923:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11924:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11925:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11926:  /*   strcpy(pathimach,argv[0]); */
                   11927:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11928:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11929:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11930: #ifdef WIN32
                   11931:   _chdir(path); /* Can be a relative path */
                   11932:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11933: #else
1.126     brouard  11934:   chdir(path); /* Can be a relative path */
1.184     brouard  11935:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11936: #endif
                   11937:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11938:   strcpy(command,"mkdir ");
                   11939:   strcat(command,optionfilefiname);
                   11940:   if((outcmd=system(command)) != 0){
1.169     brouard  11941:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11942:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11943:     /* fclose(ficlog); */
                   11944: /*     exit(1); */
                   11945:   }
                   11946: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11947: /*     perror("mkdir"); */
                   11948: /*   } */
                   11949: 
                   11950:   /*-------- arguments in the command line --------*/
                   11951: 
1.186     brouard  11952:   /* Main Log file */
1.126     brouard  11953:   strcat(filelog, optionfilefiname);
                   11954:   strcat(filelog,".log");    /* */
                   11955:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11956:     printf("Problem with logfile %s\n",filelog);
                   11957:     goto end;
                   11958:   }
                   11959:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11960:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11961:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11962:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11963:  path=%s \n\
                   11964:  optionfile=%s\n\
                   11965:  optionfilext=%s\n\
1.156     brouard  11966:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  11967: 
1.197     brouard  11968:   syscompilerinfo(1);
1.167     brouard  11969: 
1.126     brouard  11970:   printf("Local time (at start):%s",strstart);
                   11971:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   11972:   fflush(ficlog);
                   11973: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  11974: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  11975: 
                   11976:   /* */
                   11977:   strcpy(fileres,"r");
                   11978:   strcat(fileres, optionfilefiname);
1.201     brouard  11979:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  11980:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  11981:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  11982: 
1.186     brouard  11983:   /* Main ---------arguments file --------*/
1.126     brouard  11984: 
                   11985:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  11986:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   11987:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  11988:     fflush(ficlog);
1.149     brouard  11989:     /* goto end; */
                   11990:     exit(70); 
1.126     brouard  11991:   }
                   11992: 
                   11993:   strcpy(filereso,"o");
1.201     brouard  11994:   strcat(filereso,fileresu);
1.126     brouard  11995:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   11996:     printf("Problem with Output resultfile: %s\n", filereso);
                   11997:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   11998:     fflush(ficlog);
                   11999:     goto end;
                   12000:   }
1.278     brouard  12001:       /*-------- Rewriting parameter file ----------*/
                   12002:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12003:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12004:   strcat(rfileres,".");    /* */
                   12005:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12006:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12007:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12008:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12009:     fflush(ficlog);
                   12010:     goto end;
                   12011:   }
                   12012:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12013: 
1.278     brouard  12014:                                      
1.126     brouard  12015:   /* Reads comments: lines beginning with '#' */
                   12016:   numlinepar=0;
1.277     brouard  12017:   /* Is it a BOM UTF-8 Windows file? */
                   12018:   /* First parameter line */
1.197     brouard  12019:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12020:     noffset=0;
                   12021:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12022:     {
                   12023:       noffset=noffset+3;
                   12024:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12025:     }
1.302     brouard  12026: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12027:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12028:     {
                   12029:       noffset=noffset+2;
                   12030:       printf("# File is an UTF16BE BOM file\n");
                   12031:     }
                   12032:     else if( line[0] == 0 && line[1] == 0)
                   12033:     {
                   12034:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12035:        noffset=noffset+4;
                   12036:        printf("# File is an UTF16BE BOM file\n");
                   12037:       }
                   12038:     } else{
                   12039:       ;/*printf(" Not a BOM file\n");*/
                   12040:     }
                   12041:   
1.197     brouard  12042:     /* If line starts with a # it is a comment */
1.277     brouard  12043:     if (line[noffset] == '#') {
1.197     brouard  12044:       numlinepar++;
                   12045:       fputs(line,stdout);
                   12046:       fputs(line,ficparo);
1.278     brouard  12047:       fputs(line,ficres);
1.197     brouard  12048:       fputs(line,ficlog);
                   12049:       continue;
                   12050:     }else
                   12051:       break;
                   12052:   }
                   12053:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12054:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12055:     if (num_filled != 5) {
                   12056:       printf("Should be 5 parameters\n");
1.283     brouard  12057:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12058:     }
1.126     brouard  12059:     numlinepar++;
1.197     brouard  12060:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12061:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12062:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12063:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12064:   }
                   12065:   /* Second parameter line */
                   12066:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12067:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12068:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12069:     if (line[0] == '#') {
                   12070:       numlinepar++;
1.283     brouard  12071:       printf("%s",line);
                   12072:       fprintf(ficres,"%s",line);
                   12073:       fprintf(ficparo,"%s",line);
                   12074:       fprintf(ficlog,"%s",line);
1.197     brouard  12075:       continue;
                   12076:     }else
                   12077:       break;
                   12078:   }
1.223     brouard  12079:   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", \
                   12080:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12081:     if (num_filled != 11) {
                   12082:       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  12083:       printf("but line=%s\n",line);
1.283     brouard  12084:       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");
                   12085:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12086:     }
1.286     brouard  12087:     if( lastpass > maxwav){
                   12088:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12089:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12090:       fflush(ficlog);
                   12091:       goto end;
                   12092:     }
                   12093:       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  12094:     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  12095:     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  12096:     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  12097:   }
1.203     brouard  12098:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12099:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12100:   /* Third parameter line */
                   12101:   while(fgets(line, MAXLINE, ficpar)) {
                   12102:     /* If line starts with a # it is a comment */
                   12103:     if (line[0] == '#') {
                   12104:       numlinepar++;
1.283     brouard  12105:       printf("%s",line);
                   12106:       fprintf(ficres,"%s",line);
                   12107:       fprintf(ficparo,"%s",line);
                   12108:       fprintf(ficlog,"%s",line);
1.197     brouard  12109:       continue;
                   12110:     }else
                   12111:       break;
                   12112:   }
1.201     brouard  12113:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12114:     if (num_filled != 1){
1.302     brouard  12115:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12116:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12117:       model[0]='\0';
                   12118:       goto end;
                   12119:     }
                   12120:     else{
                   12121:       if (model[0]=='+'){
                   12122:        for(i=1; i<=strlen(model);i++)
                   12123:          modeltemp[i-1]=model[i];
1.201     brouard  12124:        strcpy(model,modeltemp); 
1.197     brouard  12125:       }
                   12126:     }
1.199     brouard  12127:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12128:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12129:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12130:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12131:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12132:   }
                   12133:   /* 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); */
                   12134:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12135:   /* 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  12136:   /* 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); */
                   12137:   /* 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  12138:   fflush(ficlog);
1.190     brouard  12139:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12140:   if(model[0]=='#'){
1.279     brouard  12141:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12142:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12143:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12144:     if(mle != -1){
1.279     brouard  12145:       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  12146:       exit(1);
                   12147:     }
                   12148:   }
1.126     brouard  12149:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12150:     ungetc(c,ficpar);
                   12151:     fgets(line, MAXLINE, ficpar);
                   12152:     numlinepar++;
1.195     brouard  12153:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12154:       z[0]=line[1];
                   12155:     }
                   12156:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12157:     fputs(line, stdout);
                   12158:     //puts(line);
1.126     brouard  12159:     fputs(line,ficparo);
                   12160:     fputs(line,ficlog);
                   12161:   }
                   12162:   ungetc(c,ficpar);
                   12163: 
                   12164:    
1.290     brouard  12165:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12166:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12167:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12168:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12169:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12170:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12171:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12172:   */
                   12173:   if (strlen(model)>1) 
1.187     brouard  12174:     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  12175:   else
1.187     brouard  12176:     ncovmodel=2; /* Constant and age */
1.133     brouard  12177:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12178:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12179:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12180:     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);
                   12181:     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);
                   12182:     fflush(stdout);
                   12183:     fclose (ficlog);
                   12184:     goto end;
                   12185:   }
1.126     brouard  12186:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12187:   delti=delti3[1][1];
                   12188:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12189:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12190: /* We could also provide initial parameters values giving by simple logistic regression 
                   12191:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12192:       /* for(i=1;i<nlstate;i++){ */
                   12193:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12194:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12195:       /* } */
1.126     brouard  12196:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12197:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12198:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12199:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12200:     fclose (ficparo);
                   12201:     fclose (ficlog);
                   12202:     goto end;
                   12203:     exit(0);
1.220     brouard  12204:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12205:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12206:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12207:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12208:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12209:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12210:     hess=matrix(1,npar,1,npar);
1.220     brouard  12211:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12212:     /* Read guessed parameters */
1.126     brouard  12213:     /* Reads comments: lines beginning with '#' */
                   12214:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12215:       ungetc(c,ficpar);
                   12216:       fgets(line, MAXLINE, ficpar);
                   12217:       numlinepar++;
1.141     brouard  12218:       fputs(line,stdout);
1.126     brouard  12219:       fputs(line,ficparo);
                   12220:       fputs(line,ficlog);
                   12221:     }
                   12222:     ungetc(c,ficpar);
                   12223:     
                   12224:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12225:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12226:     for(i=1; i <=nlstate; i++){
1.234     brouard  12227:       j=0;
1.126     brouard  12228:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12229:        if(jj==i) continue;
                   12230:        j++;
1.292     brouard  12231:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12232:          ungetc(c,ficpar);
                   12233:          fgets(line, MAXLINE, ficpar);
                   12234:          numlinepar++;
                   12235:          fputs(line,stdout);
                   12236:          fputs(line,ficparo);
                   12237:          fputs(line,ficlog);
                   12238:        }
                   12239:        ungetc(c,ficpar);
1.234     brouard  12240:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12241:        if ((i1 != i) || (j1 != jj)){
                   12242:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12243: It might be a problem of design; if ncovcol and the model are correct\n \
                   12244: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12245:          exit(1);
                   12246:        }
                   12247:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12248:        if(mle==1)
                   12249:          printf("%1d%1d",i,jj);
                   12250:        fprintf(ficlog,"%1d%1d",i,jj);
                   12251:        for(k=1; k<=ncovmodel;k++){
                   12252:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12253:          if(mle==1){
                   12254:            printf(" %lf",param[i][j][k]);
                   12255:            fprintf(ficlog," %lf",param[i][j][k]);
                   12256:          }
                   12257:          else
                   12258:            fprintf(ficlog," %lf",param[i][j][k]);
                   12259:          fprintf(ficparo," %lf",param[i][j][k]);
                   12260:        }
                   12261:        fscanf(ficpar,"\n");
                   12262:        numlinepar++;
                   12263:        if(mle==1)
                   12264:          printf("\n");
                   12265:        fprintf(ficlog,"\n");
                   12266:        fprintf(ficparo,"\n");
1.126     brouard  12267:       }
                   12268:     }  
                   12269:     fflush(ficlog);
1.234     brouard  12270:     
1.251     brouard  12271:     /* Reads parameters values */
1.126     brouard  12272:     p=param[1][1];
1.251     brouard  12273:     pstart=paramstart[1][1];
1.126     brouard  12274:     
                   12275:     /* Reads comments: lines beginning with '#' */
                   12276:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12277:       ungetc(c,ficpar);
                   12278:       fgets(line, MAXLINE, ficpar);
                   12279:       numlinepar++;
1.141     brouard  12280:       fputs(line,stdout);
1.126     brouard  12281:       fputs(line,ficparo);
                   12282:       fputs(line,ficlog);
                   12283:     }
                   12284:     ungetc(c,ficpar);
                   12285: 
                   12286:     for(i=1; i <=nlstate; i++){
                   12287:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12288:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12289:        if ( (i1-i) * (j1-j) != 0){
                   12290:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12291:          exit(1);
                   12292:        }
                   12293:        printf("%1d%1d",i,j);
                   12294:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12295:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12296:        for(k=1; k<=ncovmodel;k++){
                   12297:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12298:          printf(" %le",delti3[i][j][k]);
                   12299:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12300:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12301:        }
                   12302:        fscanf(ficpar,"\n");
                   12303:        numlinepar++;
                   12304:        printf("\n");
                   12305:        fprintf(ficparo,"\n");
                   12306:        fprintf(ficlog,"\n");
1.126     brouard  12307:       }
                   12308:     }
                   12309:     fflush(ficlog);
1.234     brouard  12310:     
1.145     brouard  12311:     /* Reads covariance matrix */
1.126     brouard  12312:     delti=delti3[1][1];
1.220     brouard  12313:                
                   12314:                
1.126     brouard  12315:     /* 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  12316:                
1.126     brouard  12317:     /* Reads comments: lines beginning with '#' */
                   12318:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12319:       ungetc(c,ficpar);
                   12320:       fgets(line, MAXLINE, ficpar);
                   12321:       numlinepar++;
1.141     brouard  12322:       fputs(line,stdout);
1.126     brouard  12323:       fputs(line,ficparo);
                   12324:       fputs(line,ficlog);
                   12325:     }
                   12326:     ungetc(c,ficpar);
1.220     brouard  12327:                
1.126     brouard  12328:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12329:     hess=matrix(1,npar,1,npar);
1.131     brouard  12330:     for(i=1; i <=npar; i++)
                   12331:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12332:                
1.194     brouard  12333:     /* Scans npar lines */
1.126     brouard  12334:     for(i=1; i <=npar; i++){
1.226     brouard  12335:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12336:       if(count != 3){
1.226     brouard  12337:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12338: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12339: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12340:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12341: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12342: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12343:        exit(1);
1.220     brouard  12344:       }else{
1.226     brouard  12345:        if(mle==1)
                   12346:          printf("%1d%1d%d",i1,j1,jk);
                   12347:       }
                   12348:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12349:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12350:       for(j=1; j <=i; j++){
1.226     brouard  12351:        fscanf(ficpar," %le",&matcov[i][j]);
                   12352:        if(mle==1){
                   12353:          printf(" %.5le",matcov[i][j]);
                   12354:        }
                   12355:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12356:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12357:       }
                   12358:       fscanf(ficpar,"\n");
                   12359:       numlinepar++;
                   12360:       if(mle==1)
1.220     brouard  12361:                                printf("\n");
1.126     brouard  12362:       fprintf(ficlog,"\n");
                   12363:       fprintf(ficparo,"\n");
                   12364:     }
1.194     brouard  12365:     /* End of read covariance matrix npar lines */
1.126     brouard  12366:     for(i=1; i <=npar; i++)
                   12367:       for(j=i+1;j<=npar;j++)
1.226     brouard  12368:        matcov[i][j]=matcov[j][i];
1.126     brouard  12369:     
                   12370:     if(mle==1)
                   12371:       printf("\n");
                   12372:     fprintf(ficlog,"\n");
                   12373:     
                   12374:     fflush(ficlog);
                   12375:     
                   12376:   }    /* End of mle != -3 */
1.218     brouard  12377:   
1.186     brouard  12378:   /*  Main data
                   12379:    */
1.290     brouard  12380:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12381:   /* num=lvector(1,n); */
                   12382:   /* moisnais=vector(1,n); */
                   12383:   /* annais=vector(1,n); */
                   12384:   /* moisdc=vector(1,n); */
                   12385:   /* andc=vector(1,n); */
                   12386:   /* weight=vector(1,n); */
                   12387:   /* agedc=vector(1,n); */
                   12388:   /* cod=ivector(1,n); */
                   12389:   /* for(i=1;i<=n;i++){ */
                   12390:   num=lvector(firstobs,lastobs);
                   12391:   moisnais=vector(firstobs,lastobs);
                   12392:   annais=vector(firstobs,lastobs);
                   12393:   moisdc=vector(firstobs,lastobs);
                   12394:   andc=vector(firstobs,lastobs);
                   12395:   weight=vector(firstobs,lastobs);
                   12396:   agedc=vector(firstobs,lastobs);
                   12397:   cod=ivector(firstobs,lastobs);
                   12398:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12399:     num[i]=0;
                   12400:     moisnais[i]=0;
                   12401:     annais[i]=0;
                   12402:     moisdc[i]=0;
                   12403:     andc[i]=0;
                   12404:     agedc[i]=0;
                   12405:     cod[i]=0;
                   12406:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12407:   }
1.290     brouard  12408:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12409:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12410:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12411:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12412:   tab=ivector(1,NCOVMAX);
1.144     brouard  12413:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12414:   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  12415: 
1.136     brouard  12416:   /* Reads data from file datafile */
                   12417:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12418:     goto end;
                   12419: 
                   12420:   /* Calculation of the number of parameters from char model */
1.234     brouard  12421:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12422:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12423:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12424:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12425:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12426:   */
                   12427:   
                   12428:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12429:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12430:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.234     brouard  12431:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12432:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12433:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12434:   TvarF=ivector(1,NCOVMAX); /*  */
                   12435:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12436:   TvarV=ivector(1,NCOVMAX); /*  */
                   12437:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12438:   TvarA=ivector(1,NCOVMAX); /*  */
                   12439:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12440:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12441:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12442:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12443:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12444:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12445:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12446:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12447:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12448: 
1.230     brouard  12449:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12450:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12451:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12452:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12453:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12454:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12455:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12456:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12457:   */
                   12458:   /* For model-covariate k tells which data-covariate to use but
                   12459:     because this model-covariate is a construction we invent a new column
                   12460:     ncovcol + k1
                   12461:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12462:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12463:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12464:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12465:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12466:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12467:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12468:   */
1.145     brouard  12469:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12470:   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  12471:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12472:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12473:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12474:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12475:                         4 covariates (3 plus signs)
                   12476:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12477:                           */  
                   12478:   for(i=1;i<NCOVMAX;i++)
                   12479:     Tage[i]=0;
1.230     brouard  12480:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12481:                                * individual dummy, fixed or varying:
                   12482:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12483:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12484:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12485:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12486:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12487:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12488:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12489:                                * individual quantitative, fixed or varying:
                   12490:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12491:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12492:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12493: /* Main decodemodel */
                   12494: 
1.187     brouard  12495: 
1.223     brouard  12496:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12497:     goto end;
                   12498: 
1.137     brouard  12499:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12500:     nbwarn++;
                   12501:     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); 
                   12502:     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); 
                   12503:   }
1.136     brouard  12504:     /*  if(mle==1){*/
1.137     brouard  12505:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12506:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12507:   }
                   12508: 
                   12509:     /*-calculation of age at interview from date of interview and age at death -*/
                   12510:   agev=matrix(1,maxwav,1,imx);
                   12511: 
                   12512:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12513:     goto end;
                   12514: 
1.126     brouard  12515: 
1.136     brouard  12516:   agegomp=(int)agemin;
1.290     brouard  12517:   free_vector(moisnais,firstobs,lastobs);
                   12518:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12519:   /* free_matrix(mint,1,maxwav,1,n);
                   12520:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12521:   /* free_vector(moisdc,1,n); */
                   12522:   /* free_vector(andc,1,n); */
1.145     brouard  12523:   /* */
                   12524:   
1.126     brouard  12525:   wav=ivector(1,imx);
1.214     brouard  12526:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12527:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12528:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12529:   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.*/
                   12530:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12531:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12532:    
                   12533:   /* Concatenates waves */
1.214     brouard  12534:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12535:      Death is a valid wave (if date is known).
                   12536:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12537:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12538:      and mw[mi+1][i]. dh depends on stepm.
                   12539:   */
                   12540: 
1.126     brouard  12541:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12542:   /* Concatenates waves */
1.145     brouard  12543:  
1.290     brouard  12544:   free_vector(moisdc,firstobs,lastobs);
                   12545:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12546: 
1.126     brouard  12547:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12548:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12549:   ncodemax[1]=1;
1.145     brouard  12550:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12551:   cptcoveff=0;
1.220     brouard  12552:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   12553:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  12554:   }
                   12555:   
                   12556:   ncovcombmax=pow(2,cptcoveff);
                   12557:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12558:   for(i=1;i<ncovcombmax;i++)
                   12559:     invalidvarcomb[i]=0;
                   12560:   
1.211     brouard  12561:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12562:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12563:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12564:   
1.200     brouard  12565:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12566:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12567:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12568:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12569:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12570:    * (currently 0 or 1) in the data.
                   12571:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12572:    * corresponding modality (h,j).
                   12573:    */
                   12574: 
1.145     brouard  12575:   h=0;
                   12576:   /*if (cptcovn > 0) */
1.126     brouard  12577:   m=pow(2,cptcoveff);
                   12578:  
1.144     brouard  12579:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12580:           * For k=4 covariates, h goes from 1 to m=2**k
                   12581:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12582:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12583:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12584:           *______________________________   *______________________
                   12585:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12586:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12587:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12588:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12589:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12590:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12591:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12592:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12593:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12594:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12595:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12596:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12597:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12598:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12599:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12600:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12601:           */                                     
1.212     brouard  12602:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12603:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12604:      * and the value of each covariate?
                   12605:      * V1=1, V2=1, V3=2, V4=1 ?
                   12606:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12607:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12608:      * In order to get the real value in the data, we use nbcode
                   12609:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12610:      * We are keeping this crazy system in order to be able (in the future?) 
                   12611:      * to have more than 2 values (0 or 1) for a covariate.
                   12612:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12613:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12614:      *              bbbbbbbb
                   12615:      *              76543210     
                   12616:      *   h-1        00000101 (6-1=5)
1.219     brouard  12617:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12618:      *           &
                   12619:      *     1        00000001 (1)
1.219     brouard  12620:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12621:      *          +1= 00000001 =1 
1.211     brouard  12622:      *
                   12623:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12624:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12625:      *    >>k'            11
                   12626:      *          &   00000001
                   12627:      *            = 00000001
                   12628:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12629:      * Reverse h=6 and m=16?
                   12630:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12631:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12632:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12633:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12634:      * V3=decodtabm(14,3,2**4)=2
                   12635:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12636:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12637:      *          &1 000000001
                   12638:      *           = 000000001
                   12639:      *         +1= 000000010 =2
                   12640:      *                  2211
                   12641:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12642:      *                  V3=2
1.220     brouard  12643:                 * codtabm and decodtabm are identical
1.211     brouard  12644:      */
                   12645: 
1.145     brouard  12646: 
                   12647:  free_ivector(Ndum,-1,NCOVMAX);
                   12648: 
                   12649: 
1.126     brouard  12650:     
1.186     brouard  12651:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12652:   strcpy(optionfilegnuplot,optionfilefiname);
                   12653:   if(mle==-3)
1.201     brouard  12654:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12655:   strcat(optionfilegnuplot,".gp");
                   12656: 
                   12657:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12658:     printf("Problem with file %s",optionfilegnuplot);
                   12659:   }
                   12660:   else{
1.204     brouard  12661:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12662:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12663:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12664:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12665:   }
                   12666:   /*  fclose(ficgp);*/
1.186     brouard  12667: 
                   12668: 
                   12669:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12670: 
                   12671:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12672:   if(mle==-3)
1.201     brouard  12673:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12674:   strcat(optionfilehtm,".htm");
                   12675:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12676:     printf("Problem with %s \n",optionfilehtm);
                   12677:     exit(0);
1.126     brouard  12678:   }
                   12679: 
                   12680:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12681:   strcat(optionfilehtmcov,"-cov.htm");
                   12682:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12683:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12684:   }
                   12685:   else{
                   12686:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12687: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12688: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12689:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12690:   }
                   12691: 
1.332     brouard  12692:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
1.204     brouard  12693: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   12694: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12695: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12696: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12697: \n\
                   12698: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12699:  <ul><li><h4>Parameter files</h4>\n\
                   12700:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12701:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12702:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12703:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12704:  - Date and time at start: %s</ul>\n",\
                   12705:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   12706:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12707:          fileres,fileres,\
                   12708:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12709:   fflush(fichtm);
                   12710: 
                   12711:   strcpy(pathr,path);
                   12712:   strcat(pathr,optionfilefiname);
1.184     brouard  12713: #ifdef WIN32
                   12714:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12715: #else
1.126     brouard  12716:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12717: #endif
                   12718:          
1.126     brouard  12719:   
1.220     brouard  12720:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12721:                 and for any valid combination of covariates
1.126     brouard  12722:      and prints on file fileres'p'. */
1.251     brouard  12723:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12724:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12725: 
                   12726:   fprintf(fichtm,"\n");
1.286     brouard  12727:   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  12728:          ftol, stepm);
                   12729:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12730:   ncurrv=1;
                   12731:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12732:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12733:   ncurrv=i;
                   12734:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12735:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12736:   ncurrv=i;
                   12737:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12738:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12739:   ncurrv=i;
                   12740:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12741:   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", \
                   12742:           nlstate, ndeath, maxwav, mle, weightopt);
                   12743: 
                   12744:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12745: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12746: 
                   12747:   
1.317     brouard  12748:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12749: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12750: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12751:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12752:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12753:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12754:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12755:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12756:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12757: 
1.126     brouard  12758:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12759:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12760:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12761: 
                   12762:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12763:   /* For mortality only */
1.126     brouard  12764:   if (mle==-3){
1.136     brouard  12765:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12766:     for(i=1;i<=NDIM;i++)
                   12767:       for(j=1;j<=NDIM;j++)
                   12768:        ximort[i][j]=0.;
1.186     brouard  12769:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12770:     cens=ivector(firstobs,lastobs);
                   12771:     ageexmed=vector(firstobs,lastobs);
                   12772:     agecens=vector(firstobs,lastobs);
                   12773:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12774:                
1.126     brouard  12775:     for (i=1; i<=imx; i++){
                   12776:       dcwave[i]=-1;
                   12777:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12778:        if (s[m][i]>nlstate) {
                   12779:          dcwave[i]=m;
                   12780:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12781:          break;
                   12782:        }
1.126     brouard  12783:     }
1.226     brouard  12784:     
1.126     brouard  12785:     for (i=1; i<=imx; i++) {
                   12786:       if (wav[i]>0){
1.226     brouard  12787:        ageexmed[i]=agev[mw[1][i]][i];
                   12788:        j=wav[i];
                   12789:        agecens[i]=1.; 
                   12790:        
                   12791:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12792:          agecens[i]=agev[mw[j][i]][i];
                   12793:          cens[i]= 1;
                   12794:        }else if (ageexmed[i]< 1) 
                   12795:          cens[i]= -1;
                   12796:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12797:          cens[i]=0 ;
1.126     brouard  12798:       }
                   12799:       else cens[i]=-1;
                   12800:     }
                   12801:     
                   12802:     for (i=1;i<=NDIM;i++) {
                   12803:       for (j=1;j<=NDIM;j++)
1.226     brouard  12804:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12805:     }
                   12806:     
1.302     brouard  12807:     p[1]=0.0268; p[NDIM]=0.083;
                   12808:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12809:     
                   12810:     
1.136     brouard  12811: #ifdef GSL
                   12812:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12813: #else
1.126     brouard  12814:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12815: #endif
1.201     brouard  12816:     strcpy(filerespow,"POW-MORT_"); 
                   12817:     strcat(filerespow,fileresu);
1.126     brouard  12818:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12819:       printf("Problem with resultfile: %s\n", filerespow);
                   12820:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12821:     }
1.136     brouard  12822: #ifdef GSL
                   12823:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12824: #else
1.126     brouard  12825:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12826: #endif
1.126     brouard  12827:     /*  for (i=1;i<=nlstate;i++)
                   12828:        for(j=1;j<=nlstate+ndeath;j++)
                   12829:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12830:     */
                   12831:     fprintf(ficrespow,"\n");
1.136     brouard  12832: #ifdef GSL
                   12833:     /* gsl starts here */ 
                   12834:     T = gsl_multimin_fminimizer_nmsimplex;
                   12835:     gsl_multimin_fminimizer *sfm = NULL;
                   12836:     gsl_vector *ss, *x;
                   12837:     gsl_multimin_function minex_func;
                   12838: 
                   12839:     /* Initial vertex size vector */
                   12840:     ss = gsl_vector_alloc (NDIM);
                   12841:     
                   12842:     if (ss == NULL){
                   12843:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12844:     }
                   12845:     /* Set all step sizes to 1 */
                   12846:     gsl_vector_set_all (ss, 0.001);
                   12847: 
                   12848:     /* Starting point */
1.126     brouard  12849:     
1.136     brouard  12850:     x = gsl_vector_alloc (NDIM);
                   12851:     
                   12852:     if (x == NULL){
                   12853:       gsl_vector_free(ss);
                   12854:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12855:     }
                   12856:   
                   12857:     /* Initialize method and iterate */
                   12858:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12859:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12860:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12861:     gsl_vector_set(x, 0, p[1]);
                   12862:     gsl_vector_set(x, 1, p[2]);
                   12863: 
                   12864:     minex_func.f = &gompertz_f;
                   12865:     minex_func.n = NDIM;
                   12866:     minex_func.params = (void *)&p; /* ??? */
                   12867:     
                   12868:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12869:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12870:     
                   12871:     printf("Iterations beginning .....\n\n");
                   12872:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12873: 
                   12874:     iteri=0;
                   12875:     while (rval == GSL_CONTINUE){
                   12876:       iteri++;
                   12877:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12878:       
                   12879:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12880:       fflush(0);
                   12881:       
                   12882:       if (status) 
                   12883:         break;
                   12884:       
                   12885:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12886:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12887:       
                   12888:       if (rval == GSL_SUCCESS)
                   12889:         printf ("converged to a local maximum at\n");
                   12890:       
                   12891:       printf("%5d ", iteri);
                   12892:       for (it = 0; it < NDIM; it++){
                   12893:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12894:       }
                   12895:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12896:     }
                   12897:     
                   12898:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12899:     
                   12900:     gsl_vector_free(x); /* initial values */
                   12901:     gsl_vector_free(ss); /* inital step size */
                   12902:     for (it=0; it<NDIM; it++){
                   12903:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12904:       fprintf(ficrespow," %.12lf", p[it]);
                   12905:     }
                   12906:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12907: #endif
                   12908: #ifdef POWELL
                   12909:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12910: #endif  
1.126     brouard  12911:     fclose(ficrespow);
                   12912:     
1.203     brouard  12913:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12914: 
                   12915:     for(i=1; i <=NDIM; i++)
                   12916:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12917:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12918:     
                   12919:     printf("\nCovariance matrix\n ");
1.203     brouard  12920:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12921:     for(i=1; i <=NDIM; i++) {
                   12922:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12923:                                printf("%f ",matcov[i][j]);
                   12924:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12925:       }
1.203     brouard  12926:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12927:     }
                   12928:     
                   12929:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12930:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12931:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12932:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12933:     }
1.302     brouard  12934:     lsurv=vector(agegomp,AGESUP);
                   12935:     lpop=vector(agegomp,AGESUP);
                   12936:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12937:     lsurv[agegomp]=100000;
                   12938:     
                   12939:     for (k=agegomp;k<=AGESUP;k++) {
                   12940:       agemortsup=k;
                   12941:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12942:     }
                   12943:     
                   12944:     for (k=agegomp;k<agemortsup;k++)
                   12945:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12946:     
                   12947:     for (k=agegomp;k<agemortsup;k++){
                   12948:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12949:       sumlpop=sumlpop+lpop[k];
                   12950:     }
                   12951:     
                   12952:     tpop[agegomp]=sumlpop;
                   12953:     for (k=agegomp;k<(agemortsup-3);k++){
                   12954:       /*  tpop[k+1]=2;*/
                   12955:       tpop[k+1]=tpop[k]-lpop[k];
                   12956:     }
                   12957:     
                   12958:     
                   12959:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   12960:     for (k=agegomp;k<(agemortsup-2);k++) 
                   12961:       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]);
                   12962:     
                   12963:     
                   12964:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  12965:                ageminpar=50;
                   12966:                agemaxpar=100;
1.194     brouard  12967:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   12968:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12969: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12970: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   12971:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   12972: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   12973: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  12974:     }else{
                   12975:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   12976:                        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  12977:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  12978:                }
1.201     brouard  12979:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  12980:                     stepm, weightopt,\
                   12981:                     model,imx,p,matcov,agemortsup);
                   12982:     
1.302     brouard  12983:     free_vector(lsurv,agegomp,AGESUP);
                   12984:     free_vector(lpop,agegomp,AGESUP);
                   12985:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  12986:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  12987:     free_ivector(dcwave,firstobs,lastobs);
                   12988:     free_vector(agecens,firstobs,lastobs);
                   12989:     free_vector(ageexmed,firstobs,lastobs);
                   12990:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  12991: #ifdef GSL
1.136     brouard  12992: #endif
1.186     brouard  12993:   } /* Endof if mle==-3 mortality only */
1.205     brouard  12994:   /* Standard  */
                   12995:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   12996:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   12997:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  12998:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  12999:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13000:     for (k=1; k<=npar;k++)
                   13001:       printf(" %d %8.5f",k,p[k]);
                   13002:     printf("\n");
1.205     brouard  13003:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13004:       /* mlikeli uses func not funcone */
1.247     brouard  13005:       /* for(i=1;i<nlstate;i++){ */
                   13006:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13007:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13008:       /* } */
1.205     brouard  13009:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13010:     }
                   13011:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13012:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13013:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13014:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13015:     }
                   13016:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13017:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13018:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13019:     for (k=1; k<=npar;k++)
                   13020:       printf(" %d %8.5f",k,p[k]);
                   13021:     printf("\n");
                   13022:     
                   13023:     /*--------- results files --------------*/
1.283     brouard  13024:     /* 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  13025:     
                   13026:     
                   13027:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13028:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13029:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13030: 
                   13031:     printf("#model=  1      +     age ");
                   13032:     fprintf(ficres,"#model=  1      +     age ");
                   13033:     fprintf(ficlog,"#model=  1      +     age ");
                   13034:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13035: </ul>", model);
                   13036: 
                   13037:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13038:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13039:     if(nagesqr==1){
                   13040:       printf("  + age*age  ");
                   13041:       fprintf(ficres,"  + age*age  ");
                   13042:       fprintf(ficlog,"  + age*age  ");
                   13043:       fprintf(fichtm, "<th>+ age*age</th>");
                   13044:     }
                   13045:     for(j=1;j <=ncovmodel-2;j++){
                   13046:       if(Typevar[j]==0) {
                   13047:        printf("  +      V%d  ",Tvar[j]);
                   13048:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13049:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13050:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13051:       }else if(Typevar[j]==1) {
                   13052:        printf("  +    V%d*age ",Tvar[j]);
                   13053:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13054:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13055:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13056:       }else if(Typevar[j]==2) {
                   13057:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13058:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13059:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13060:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13061:       }
                   13062:     }
                   13063:     printf("\n");
                   13064:     fprintf(ficres,"\n");
                   13065:     fprintf(ficlog,"\n");
                   13066:     fprintf(fichtm, "</tr>");
                   13067:     fprintf(fichtm, "\n");
                   13068:     
                   13069:     
1.126     brouard  13070:     for(i=1,jk=1; i <=nlstate; i++){
                   13071:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13072:        if (k != i) {
1.319     brouard  13073:          fprintf(fichtm, "<tr>");
1.225     brouard  13074:          printf("%d%d ",i,k);
                   13075:          fprintf(ficlog,"%d%d ",i,k);
                   13076:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13077:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13078:          for(j=1; j <=ncovmodel; j++){
                   13079:            printf("%12.7f ",p[jk]);
                   13080:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13081:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13082:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13083:            jk++; 
                   13084:          }
                   13085:          printf("\n");
                   13086:          fprintf(ficlog,"\n");
                   13087:          fprintf(ficres,"\n");
1.319     brouard  13088:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13089:        }
1.126     brouard  13090:       }
                   13091:     }
1.319     brouard  13092:     /* fprintf(fichtm,"</tr>\n"); */
                   13093:     fprintf(fichtm,"</table>\n");
                   13094:     fprintf(fichtm, "\n");
                   13095: 
1.203     brouard  13096:     if(mle != 0){
                   13097:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13098:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13099:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13100:       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");
                   13101:       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  13102:       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  13103:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13104:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13105:       if(nagesqr==1){
                   13106:        printf("  + age*age  ");
                   13107:        fprintf(ficres,"  + age*age  ");
                   13108:        fprintf(ficlog,"  + age*age  ");
                   13109:        fprintf(fichtm, "<th>+ age*age</th>");
                   13110:       }
                   13111:       for(j=1;j <=ncovmodel-2;j++){
                   13112:        if(Typevar[j]==0) {
                   13113:          printf("  +      V%d  ",Tvar[j]);
                   13114:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13115:        }else if(Typevar[j]==1) {
                   13116:          printf("  +    V%d*age ",Tvar[j]);
                   13117:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13118:        }else if(Typevar[j]==2) {
                   13119:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13120:        }
                   13121:       }
                   13122:       fprintf(fichtm, "</tr>\n");
                   13123:  
1.203     brouard  13124:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13125:        for(k=1; k <=(nlstate+ndeath); k++){
                   13126:          if (k != i) {
1.319     brouard  13127:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13128:            printf("%d%d ",i,k);
                   13129:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13130:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13131:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13132:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13133:              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]));
                   13134:              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  13135:              if(fabs(wald) > 1.96){
1.321     brouard  13136:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13137:              }else{
                   13138:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13139:              }
1.324     brouard  13140:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13141:              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  13142:              jk++; 
                   13143:            }
                   13144:            printf("\n");
                   13145:            fprintf(ficlog,"\n");
1.319     brouard  13146:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13147:          }
                   13148:        }
1.193     brouard  13149:       }
1.203     brouard  13150:     } /* end of hesscov and Wald tests */
1.319     brouard  13151:     fprintf(fichtm,"</table>\n");
1.225     brouard  13152:     
1.203     brouard  13153:     /*  */
1.126     brouard  13154:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13155:     printf("# Scales (for hessian or gradient estimation)\n");
                   13156:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13157:     for(i=1,jk=1; i <=nlstate; i++){
                   13158:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13159:        if (j!=i) {
                   13160:          fprintf(ficres,"%1d%1d",i,j);
                   13161:          printf("%1d%1d",i,j);
                   13162:          fprintf(ficlog,"%1d%1d",i,j);
                   13163:          for(k=1; k<=ncovmodel;k++){
                   13164:            printf(" %.5e",delti[jk]);
                   13165:            fprintf(ficlog," %.5e",delti[jk]);
                   13166:            fprintf(ficres," %.5e",delti[jk]);
                   13167:            jk++;
                   13168:          }
                   13169:          printf("\n");
                   13170:          fprintf(ficlog,"\n");
                   13171:          fprintf(ficres,"\n");
                   13172:        }
1.126     brouard  13173:       }
                   13174:     }
                   13175:     
                   13176:     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  13177:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13178:       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");
                   13179:     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");
                   13180:     /* # 121 Var(a12)\n\ */
                   13181:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13182:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13183:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13184:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13185:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13186:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13187:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13188:     
                   13189:     
                   13190:     /* Just to have a covariance matrix which will be more understandable
                   13191:        even is we still don't want to manage dictionary of variables
                   13192:     */
                   13193:     for(itimes=1;itimes<=2;itimes++){
                   13194:       jj=0;
                   13195:       for(i=1; i <=nlstate; i++){
1.225     brouard  13196:        for(j=1; j <=nlstate+ndeath; j++){
                   13197:          if(j==i) continue;
                   13198:          for(k=1; k<=ncovmodel;k++){
                   13199:            jj++;
                   13200:            ca[0]= k+'a'-1;ca[1]='\0';
                   13201:            if(itimes==1){
                   13202:              if(mle>=1)
                   13203:                printf("#%1d%1d%d",i,j,k);
                   13204:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13205:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13206:            }else{
                   13207:              if(mle>=1)
                   13208:                printf("%1d%1d%d",i,j,k);
                   13209:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13210:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13211:            }
                   13212:            ll=0;
                   13213:            for(li=1;li <=nlstate; li++){
                   13214:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13215:                if(lj==li) continue;
                   13216:                for(lk=1;lk<=ncovmodel;lk++){
                   13217:                  ll++;
                   13218:                  if(ll<=jj){
                   13219:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13220:                    if(ll<jj){
                   13221:                      if(itimes==1){
                   13222:                        if(mle>=1)
                   13223:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13224:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13225:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13226:                      }else{
                   13227:                        if(mle>=1)
                   13228:                          printf(" %.5e",matcov[jj][ll]); 
                   13229:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13230:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13231:                      }
                   13232:                    }else{
                   13233:                      if(itimes==1){
                   13234:                        if(mle>=1)
                   13235:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13236:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13237:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13238:                      }else{
                   13239:                        if(mle>=1)
                   13240:                          printf(" %.7e",matcov[jj][ll]); 
                   13241:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13242:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13243:                      }
                   13244:                    }
                   13245:                  }
                   13246:                } /* end lk */
                   13247:              } /* end lj */
                   13248:            } /* end li */
                   13249:            if(mle>=1)
                   13250:              printf("\n");
                   13251:            fprintf(ficlog,"\n");
                   13252:            fprintf(ficres,"\n");
                   13253:            numlinepar++;
                   13254:          } /* end k*/
                   13255:        } /*end j */
1.126     brouard  13256:       } /* end i */
                   13257:     } /* end itimes */
                   13258:     
                   13259:     fflush(ficlog);
                   13260:     fflush(ficres);
1.225     brouard  13261:     while(fgets(line, MAXLINE, ficpar)) {
                   13262:       /* If line starts with a # it is a comment */
                   13263:       if (line[0] == '#') {
                   13264:        numlinepar++;
                   13265:        fputs(line,stdout);
                   13266:        fputs(line,ficparo);
                   13267:        fputs(line,ficlog);
1.299     brouard  13268:        fputs(line,ficres);
1.225     brouard  13269:        continue;
                   13270:       }else
                   13271:        break;
                   13272:     }
                   13273:     
1.209     brouard  13274:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13275:     /*   ungetc(c,ficpar); */
                   13276:     /*   fgets(line, MAXLINE, ficpar); */
                   13277:     /*   fputs(line,stdout); */
                   13278:     /*   fputs(line,ficparo); */
                   13279:     /* } */
                   13280:     /* ungetc(c,ficpar); */
1.126     brouard  13281:     
                   13282:     estepm=0;
1.209     brouard  13283:     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  13284:       
                   13285:       if (num_filled != 6) {
                   13286:        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);
                   13287:        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);
                   13288:        goto end;
                   13289:       }
                   13290:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13291:     }
                   13292:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13293:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13294:     
1.209     brouard  13295:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13296:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13297:     if (fage <= 2) {
                   13298:       bage = ageminpar;
                   13299:       fage = agemaxpar;
                   13300:     }
                   13301:     
                   13302:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13303:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13304:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13305:                
1.186     brouard  13306:     /* Other stuffs, more or less useful */    
1.254     brouard  13307:     while(fgets(line, MAXLINE, ficpar)) {
                   13308:       /* If line starts with a # it is a comment */
                   13309:       if (line[0] == '#') {
                   13310:        numlinepar++;
                   13311:        fputs(line,stdout);
                   13312:        fputs(line,ficparo);
                   13313:        fputs(line,ficlog);
1.299     brouard  13314:        fputs(line,ficres);
1.254     brouard  13315:        continue;
                   13316:       }else
                   13317:        break;
                   13318:     }
                   13319: 
                   13320:     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){
                   13321:       
                   13322:       if (num_filled != 7) {
                   13323:        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);
                   13324:        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);
                   13325:        goto end;
                   13326:       }
                   13327:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13328:       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);
                   13329:       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);
                   13330:       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  13331:     }
1.254     brouard  13332: 
                   13333:     while(fgets(line, MAXLINE, ficpar)) {
                   13334:       /* If line starts with a # it is a comment */
                   13335:       if (line[0] == '#') {
                   13336:        numlinepar++;
                   13337:        fputs(line,stdout);
                   13338:        fputs(line,ficparo);
                   13339:        fputs(line,ficlog);
1.299     brouard  13340:        fputs(line,ficres);
1.254     brouard  13341:        continue;
                   13342:       }else
                   13343:        break;
1.126     brouard  13344:     }
                   13345:     
                   13346:     
                   13347:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13348:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13349:     
1.254     brouard  13350:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13351:       if (num_filled != 1) {
                   13352:        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);
                   13353:        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);
                   13354:        goto end;
                   13355:       }
                   13356:       printf("pop_based=%d\n",popbased);
                   13357:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13358:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13359:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13360:     }
                   13361:      
1.258     brouard  13362:     /* Results */
1.332     brouard  13363:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13364:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13365:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13366:     endishere=0;
1.258     brouard  13367:     nresult=0;
1.308     brouard  13368:     parameterline=0;
1.258     brouard  13369:     do{
                   13370:       if(!fgets(line, MAXLINE, ficpar)){
                   13371:        endishere=1;
1.308     brouard  13372:        parameterline=15;
1.258     brouard  13373:       }else if (line[0] == '#') {
                   13374:        /* If line starts with a # it is a comment */
1.254     brouard  13375:        numlinepar++;
                   13376:        fputs(line,stdout);
                   13377:        fputs(line,ficparo);
                   13378:        fputs(line,ficlog);
1.299     brouard  13379:        fputs(line,ficres);
1.254     brouard  13380:        continue;
1.258     brouard  13381:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13382:        parameterline=11;
1.296     brouard  13383:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13384:        parameterline=12;
1.307     brouard  13385:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13386:        parameterline=13;
1.307     brouard  13387:       }
1.258     brouard  13388:       else{
                   13389:        parameterline=14;
1.254     brouard  13390:       }
1.308     brouard  13391:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13392:       case 11:
1.296     brouard  13393:        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)){
                   13394:                  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  13395:          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);
                   13396:          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);
                   13397:          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);
                   13398:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13399:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13400:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13401:           prvforecast = 1;
                   13402:        } 
                   13403:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13404:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13405:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13406:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13407:           prvforecast = 2;
                   13408:        }
                   13409:        else {
                   13410:          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);
                   13411:          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);
                   13412:          goto end;
1.258     brouard  13413:        }
1.254     brouard  13414:        break;
1.258     brouard  13415:       case 12:
1.296     brouard  13416:        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)){
                   13417:           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);
                   13418:          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);
                   13419:          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);
                   13420:          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);
                   13421:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13422:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13423:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13424:           prvbackcast = 1;
                   13425:        } 
                   13426:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13427:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13428:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13429:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13430:           prvbackcast = 2;
                   13431:        }
                   13432:        else {
                   13433:          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);
                   13434:          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);
                   13435:          goto end;
1.258     brouard  13436:        }
1.230     brouard  13437:        break;
1.258     brouard  13438:       case 13:
1.332     brouard  13439:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13440:        nresult++; /* Sum of resultlines */
1.332     brouard  13441:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13442:        /* removefirstspace(&resultlineori); */
                   13443:        
                   13444:        if(strstr(resultlineori,"v") !=0){
                   13445:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13446:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13447:          return 1;
                   13448:        }
                   13449:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13450:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13451:        if(nresult > MAXRESULTLINESPONE-1){
                   13452:          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);
                   13453:          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  13454:          goto end;
                   13455:        }
1.332     brouard  13456:        
1.310     brouard  13457:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13458:          fprintf(ficparo,"result: %s\n",resultline);
                   13459:          fprintf(ficres,"result: %s\n",resultline);
                   13460:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13461:        } else
                   13462:          goto end;
1.307     brouard  13463:        break;
                   13464:       case 14:
                   13465:        printf("Error: Unknown command '%s'\n",line);
                   13466:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13467:        if(line[0] == ' ' || line[0] == '\n'){
                   13468:          printf("It should not be an empty line '%s'\n",line);
                   13469:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13470:        }         
1.307     brouard  13471:        if(ncovmodel >=2 && nresult==0 ){
                   13472:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13473:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13474:        }
1.307     brouard  13475:        /* goto end; */
                   13476:        break;
1.308     brouard  13477:       case 15:
                   13478:        printf("End of resultlines.\n");
                   13479:        fprintf(ficlog,"End of resultlines.\n");
                   13480:        break;
                   13481:       default: /* parameterline =0 */
1.307     brouard  13482:        nresult=1;
                   13483:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13484:       } /* End switch parameterline */
                   13485:     }while(endishere==0); /* End do */
1.126     brouard  13486:     
1.230     brouard  13487:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13488:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13489:     
                   13490:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13491:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13492:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13493: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13494: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13495:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13496: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13497: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13498:     }else{
1.270     brouard  13499:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13500:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13501:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13502:       if(prvforecast==1){
                   13503:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13504:         jprojd=jproj1;
                   13505:         mprojd=mproj1;
                   13506:         anprojd=anproj1;
                   13507:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13508:         jprojf=jproj2;
                   13509:         mprojf=mproj2;
                   13510:         anprojf=anproj2;
                   13511:       } else if(prvforecast == 2){
                   13512:         dateprojd=dateintmean;
                   13513:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13514:         dateprojf=dateintmean+yrfproj;
                   13515:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13516:       }
                   13517:       if(prvbackcast==1){
                   13518:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13519:         jbackd=jback1;
                   13520:         mbackd=mback1;
                   13521:         anbackd=anback1;
                   13522:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13523:         jbackf=jback2;
                   13524:         mbackf=mback2;
                   13525:         anbackf=anback2;
                   13526:       } else if(prvbackcast == 2){
                   13527:         datebackd=dateintmean;
                   13528:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13529:         datebackf=dateintmean-yrbproj;
                   13530:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13531:       }
                   13532:       
                   13533:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13534:     }
                   13535:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13536:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13537:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13538:                
1.225     brouard  13539:     /*------------ free_vector  -------------*/
                   13540:     /*  chdir(path); */
1.220     brouard  13541:                
1.215     brouard  13542:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13543:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13544:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13545:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13546:     free_lvector(num,firstobs,lastobs);
                   13547:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13548:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13549:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13550:     fclose(ficparo);
                   13551:     fclose(ficres);
1.220     brouard  13552:                
                   13553:                
1.186     brouard  13554:     /* Other results (useful)*/
1.220     brouard  13555:                
                   13556:                
1.126     brouard  13557:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13558:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13559:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13560:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13561:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13562:     fclose(ficrespl);
                   13563: 
                   13564:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13565:     /*#include "hpijx.h"*/
1.332     brouard  13566:     /** 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?*/
                   13567:     /* calls hpxij with combination k */
1.180     brouard  13568:     hPijx(p, bage, fage);
1.145     brouard  13569:     fclose(ficrespij);
1.227     brouard  13570:     
1.220     brouard  13571:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13572:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13573:     k=1;
1.126     brouard  13574:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13575:     
1.269     brouard  13576:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13577:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13578:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13579:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13580:        for(k=1;k<=ncovcombmax;k++)
                   13581:          probs[i][j][k]=0.;
1.269     brouard  13582:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13583:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13584:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13585:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13586:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13587:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13588:          for(k=1;k<=ncovcombmax;k++)
                   13589:            mobaverages[i][j][k]=0.;
1.219     brouard  13590:       mobaverage=mobaverages;
                   13591:       if (mobilav!=0) {
1.235     brouard  13592:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13593:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13594:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13595:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13596:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13597:        }
1.269     brouard  13598:       } else if (mobilavproj !=0) {
1.235     brouard  13599:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13600:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13601:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13602:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13603:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13604:        }
1.269     brouard  13605:       }else{
                   13606:        printf("Internal error moving average\n");
                   13607:        fflush(stdout);
                   13608:        exit(1);
1.219     brouard  13609:       }
                   13610:     }/* end if moving average */
1.227     brouard  13611:     
1.126     brouard  13612:     /*---------- Forecasting ------------------*/
1.296     brouard  13613:     if(prevfcast==1){ 
                   13614:       /*   /\*    if(stepm ==1){*\/ */
                   13615:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13616:       /*This done previously after freqsummary.*/
                   13617:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13618:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13619:       
                   13620:       /* } else if (prvforecast==2){ */
                   13621:       /*   /\*    if(stepm ==1){*\/ */
                   13622:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13623:       /* } */
                   13624:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13625:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13626:     }
1.269     brouard  13627: 
1.296     brouard  13628:     /* Prevbcasting */
                   13629:     if(prevbcast==1){
1.219     brouard  13630:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13631:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13632:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13633: 
                   13634:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13635: 
                   13636:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13637: 
1.219     brouard  13638:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13639:       fclose(ficresplb);
                   13640: 
1.222     brouard  13641:       hBijx(p, bage, fage, mobaverage);
                   13642:       fclose(ficrespijb);
1.219     brouard  13643: 
1.296     brouard  13644:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13645:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13646:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13647:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13648:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13649:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13650: 
                   13651:       
1.269     brouard  13652:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13653: 
                   13654:       
1.269     brouard  13655:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13656:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13657:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13658:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13659:     }    /* end  Prevbcasting */
1.268     brouard  13660:  
1.186     brouard  13661:  
                   13662:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13663: 
1.215     brouard  13664:     free_ivector(wav,1,imx);
                   13665:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13666:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13667:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13668:                
                   13669:                
1.127     brouard  13670:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13671:                
1.201     brouard  13672:     strcpy(filerese,"E_");
                   13673:     strcat(filerese,fileresu);
1.126     brouard  13674:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13675:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13676:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13677:     }
1.208     brouard  13678:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13679:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13680: 
                   13681:     pstamp(ficreseij);
1.219     brouard  13682:                
1.235     brouard  13683:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13684:     if (cptcovn < 1){i1=1;}
                   13685:     
                   13686:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13687:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13688:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13689:        continue;
1.219     brouard  13690:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13691:       printf("\n#****** ");
1.225     brouard  13692:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13693:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13694:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13695:       }
                   13696:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.334   ! brouard  13697:        printf(" V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
        !          13698:        fprintf(ficreseij,"V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  13699:       }
                   13700:       fprintf(ficreseij,"******\n");
1.235     brouard  13701:       printf("******\n");
1.219     brouard  13702:       
                   13703:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13704:       oldm=oldms;savm=savms;
1.330     brouard  13705:       /* 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  13706:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13707:       
1.219     brouard  13708:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13709:     }
                   13710:     fclose(ficreseij);
1.208     brouard  13711:     printf("done evsij\n");fflush(stdout);
                   13712:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13713: 
1.218     brouard  13714:                
1.227     brouard  13715:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13716:                
1.201     brouard  13717:     strcpy(filerest,"T_");
                   13718:     strcat(filerest,fileresu);
1.127     brouard  13719:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13720:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13721:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13722:     }
1.208     brouard  13723:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13724:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13725:     strcpy(fileresstde,"STDE_");
                   13726:     strcat(fileresstde,fileresu);
1.126     brouard  13727:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13728:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13729:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13730:     }
1.227     brouard  13731:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13732:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13733: 
1.201     brouard  13734:     strcpy(filerescve,"CVE_");
                   13735:     strcat(filerescve,fileresu);
1.126     brouard  13736:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13737:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13738:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13739:     }
1.227     brouard  13740:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13741:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13742: 
1.201     brouard  13743:     strcpy(fileresv,"V_");
                   13744:     strcat(fileresv,fileresu);
1.126     brouard  13745:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13746:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13747:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13748:     }
1.227     brouard  13749:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13750:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13751: 
1.235     brouard  13752:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13753:     if (cptcovn < 1){i1=1;}
                   13754:     
1.334   ! brouard  13755:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
        !          13756:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
        !          13757:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
        !          13758:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
        !          13759:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
        !          13760:       /* */
        !          13761:       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  13762:        continue;
1.321     brouard  13763:       printf("\n# model %s \n#****** Result for:", model);
                   13764:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13765:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334   ! brouard  13766:       /* It might not be a good idea to mix dummies and quantitative */
        !          13767:       /* 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 *\/ */
        !          13768:       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 */
        !          13769:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
        !          13770:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
        !          13771:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
        !          13772:         * (V5 is quanti) V4 and V3 are dummies
        !          13773:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
        !          13774:         *                                                              l=1 l=2
        !          13775:         *                                                           k=1  1   1   0   0
        !          13776:         *                                                           k=2  2   1   1   0
        !          13777:         *                                                           k=3 [1] [2]  0   1
        !          13778:         *                                                           k=4  2   2   1   1
        !          13779:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
        !          13780:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
        !          13781:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
        !          13782:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
        !          13783:         */
        !          13784:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
        !          13785:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
        !          13786: /* We give up with the combinations!! */
        !          13787:        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 */
        !          13788: 
        !          13789:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
        !          13790:          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  */
        !          13791:          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  */
        !          13792:          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  */
        !          13793:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
        !          13794:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
        !          13795:          }else{
        !          13796:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
        !          13797:          }
        !          13798:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          13799:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          13800:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
        !          13801:          /* For each selected (single) quantitative value */
        !          13802:          printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
        !          13803:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
        !          13804:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
        !          13805:          }else{
        !          13806:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
        !          13807:          }
        !          13808:        }else{
        !          13809:          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 */
        !          13810:          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 */
        !          13811:          exit(1);
        !          13812:        }
1.227     brouard  13813:       }
1.334   ! brouard  13814:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
        !          13815:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
        !          13816:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          13817:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
        !          13818:       /* }      */
1.208     brouard  13819:       fprintf(ficrest,"******\n");
1.227     brouard  13820:       fprintf(ficlog,"******\n");
                   13821:       printf("******\n");
1.208     brouard  13822:       
                   13823:       fprintf(ficresstdeij,"\n#****** ");
                   13824:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13825:       for(j=1;j<=cptcoveff;j++) {
1.334   ! brouard  13826:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
        !          13827:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          13828:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          13829:       }
        !          13830:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
        !          13831:        fprintf(ficresstdeij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
        !          13832:        fprintf(ficrescveij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  13833:       }        
1.208     brouard  13834:       fprintf(ficresstdeij,"******\n");
                   13835:       fprintf(ficrescveij,"******\n");
                   13836:       
                   13837:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13838:       /* pstamp(ficresvij); */
1.225     brouard  13839:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  13840:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]);
1.235     brouard  13841:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13842:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   13843:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  13844:       }        
1.208     brouard  13845:       fprintf(ficresvij,"******\n");
                   13846:       
                   13847:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13848:       oldm=oldms;savm=savms;
1.235     brouard  13849:       printf(" cvevsij ");
                   13850:       fprintf(ficlog, " cvevsij ");
                   13851:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13852:       printf(" end cvevsij \n ");
                   13853:       fprintf(ficlog, " end cvevsij \n ");
                   13854:       
                   13855:       /*
                   13856:        */
                   13857:       /* goto endfree; */
                   13858:       
                   13859:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13860:       pstamp(ficrest);
                   13861:       
1.269     brouard  13862:       epj=vector(1,nlstate+1);
1.208     brouard  13863:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13864:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13865:        cptcod= 0; /* To be deleted */
                   13866:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13867:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13868:        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  13869:        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 ");
                   13870:        if(vpopbased==1)
                   13871:          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);
                   13872:        else
1.288     brouard  13873:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13874:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   13875:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13876:        fprintf(ficrest,"\n");
                   13877:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13878:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13879:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13880:        for(age=bage; age <=fage ;age++){
1.235     brouard  13881:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13882:          if (vpopbased==1) {
                   13883:            if(mobilav ==0){
                   13884:              for(i=1; i<=nlstate;i++)
                   13885:                prlim[i][i]=probs[(int)age][i][k];
                   13886:            }else{ /* mobilav */ 
                   13887:              for(i=1; i<=nlstate;i++)
                   13888:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13889:            }
                   13890:          }
1.219     brouard  13891:          
1.227     brouard  13892:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13893:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13894:          /* printf(" age %4.0f ",age); */
                   13895:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13896:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13897:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13898:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13899:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13900:            }
                   13901:            epj[nlstate+1] +=epj[j];
                   13902:          }
                   13903:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13904:          
1.227     brouard  13905:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13906:            for(j=1;j <=nlstate;j++)
                   13907:              vepp += vareij[i][j][(int)age];
                   13908:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13909:          for(j=1;j <=nlstate;j++){
                   13910:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13911:          }
                   13912:          fprintf(ficrest,"\n");
                   13913:        }
1.208     brouard  13914:       } /* End vpopbased */
1.269     brouard  13915:       free_vector(epj,1,nlstate+1);
1.208     brouard  13916:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13917:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13918:       printf("done selection\n");fflush(stdout);
                   13919:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13920:       
1.235     brouard  13921:     } /* End k selection */
1.227     brouard  13922: 
                   13923:     printf("done State-specific expectancies\n");fflush(stdout);
                   13924:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13925: 
1.288     brouard  13926:     /* variance-covariance of forward period prevalence*/
1.269     brouard  13927:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13928: 
1.227     brouard  13929:     
1.290     brouard  13930:     free_vector(weight,firstobs,lastobs);
1.330     brouard  13931:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13932:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13933:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13934:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13935:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13936:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13937:     free_ivector(tab,1,NCOVMAX);
                   13938:     fclose(ficresstdeij);
                   13939:     fclose(ficrescveij);
                   13940:     fclose(ficresvij);
                   13941:     fclose(ficrest);
                   13942:     fclose(ficpar);
                   13943:     
                   13944:     
1.126     brouard  13945:     /*---------- End : free ----------------*/
1.219     brouard  13946:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13947:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13948:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13949:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13950:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13951:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13952:   /* endfree:*/
                   13953:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13954:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   13955:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  13956:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   13957:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   13958:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   13959:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  13960:   free_matrix(matcov,1,npar,1,npar);
                   13961:   free_matrix(hess,1,npar,1,npar);
                   13962:   /*free_vector(delti,1,npar);*/
                   13963:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13964:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  13965:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  13966:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   13967:   
                   13968:   free_ivector(ncodemax,1,NCOVMAX);
                   13969:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   13970:   free_ivector(Dummy,-1,NCOVMAX);
                   13971:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  13972:   free_ivector(DummyV,1,NCOVMAX);
                   13973:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  13974:   free_ivector(Typevar,-1,NCOVMAX);
                   13975:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  13976:   free_ivector(TvarsQ,1,NCOVMAX);
                   13977:   free_ivector(TvarsQind,1,NCOVMAX);
                   13978:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  13979:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  13980:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  13981:   free_ivector(TvarFD,1,NCOVMAX);
                   13982:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  13983:   free_ivector(TvarF,1,NCOVMAX);
                   13984:   free_ivector(TvarFind,1,NCOVMAX);
                   13985:   free_ivector(TvarV,1,NCOVMAX);
                   13986:   free_ivector(TvarVind,1,NCOVMAX);
                   13987:   free_ivector(TvarA,1,NCOVMAX);
                   13988:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  13989:   free_ivector(TvarFQ,1,NCOVMAX);
                   13990:   free_ivector(TvarFQind,1,NCOVMAX);
                   13991:   free_ivector(TvarVD,1,NCOVMAX);
                   13992:   free_ivector(TvarVDind,1,NCOVMAX);
                   13993:   free_ivector(TvarVQ,1,NCOVMAX);
                   13994:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  13995:   free_ivector(Tvarsel,1,NCOVMAX);
                   13996:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  13997:   free_ivector(Tposprod,1,NCOVMAX);
                   13998:   free_ivector(Tprod,1,NCOVMAX);
                   13999:   free_ivector(Tvaraff,1,NCOVMAX);
                   14000:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   14001:   free_ivector(Tage,1,NCOVMAX);
                   14002:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14003:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14004:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14005: 
                   14006:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14007: 
1.227     brouard  14008:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14009:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14010:   fflush(fichtm);
                   14011:   fflush(ficgp);
                   14012:   
1.227     brouard  14013:   
1.126     brouard  14014:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14015:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14016:     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  14017:   }else{
                   14018:     printf("End of Imach\n");
                   14019:     fprintf(ficlog,"End of Imach\n");
                   14020:   }
                   14021:   printf("See log file on %s\n",filelog);
                   14022:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14023:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14024:   rend_time = time(NULL);  
                   14025:   end_time = *localtime(&rend_time);
                   14026:   /* tml = *localtime(&end_time.tm_sec); */
                   14027:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14028:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14029:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14030:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14031:   
1.157     brouard  14032:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14033:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14034:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14035:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14036: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14037:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14038:   fclose(fichtm);
                   14039:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14040:   fclose(fichtmcov);
                   14041:   fclose(ficgp);
                   14042:   fclose(ficlog);
                   14043:   /*------ End -----------*/
1.227     brouard  14044:   
1.281     brouard  14045: 
                   14046: /* Executes gnuplot */
1.227     brouard  14047:   
                   14048:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14049: #ifdef WIN32
1.227     brouard  14050:   if (_chdir(pathcd) != 0)
                   14051:     printf("Can't move to directory %s!\n",path);
                   14052:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14053: #else
1.227     brouard  14054:     if(chdir(pathcd) != 0)
                   14055:       printf("Can't move to directory %s!\n", path);
                   14056:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14057: #endif 
1.126     brouard  14058:     printf("Current directory %s!\n",pathcd);
                   14059:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14060:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14061: #ifdef _WIN32
1.126     brouard  14062:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14063: #endif
                   14064:   if(!stat(plotcmd,&info)){
1.158     brouard  14065:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14066:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14067:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14068:     }else
                   14069:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14070: #ifdef __unix
1.126     brouard  14071:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14072:     if(!stat(plotcmd,&info)){
1.158     brouard  14073:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14074:     }else
                   14075:       strcpy(pplotcmd,plotcmd);
                   14076: #endif
                   14077:   }else
                   14078:     strcpy(pplotcmd,plotcmd);
                   14079:   
                   14080:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14081:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14082:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14083:   
1.126     brouard  14084:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14085:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14086:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14087:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14088:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14089:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14090:       strcpy(plotcmd,pplotcmd);
                   14091:     }
1.126     brouard  14092:   }
1.158     brouard  14093:   printf(" Successful, please wait...");
1.126     brouard  14094:   while (z[0] != 'q') {
                   14095:     /* chdir(path); */
1.154     brouard  14096:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14097:     scanf("%s",z);
                   14098: /*     if (z[0] == 'c') system("./imach"); */
                   14099:     if (z[0] == 'e') {
1.158     brouard  14100: #ifdef __APPLE__
1.152     brouard  14101:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14102: #elif __linux
                   14103:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14104: #else
1.152     brouard  14105:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14106: #endif
                   14107:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14108:       system(pplotcmd);
1.126     brouard  14109:     }
                   14110:     else if (z[0] == 'g') system(plotcmd);
                   14111:     else if (z[0] == 'q') exit(0);
                   14112:   }
1.227     brouard  14113: end:
1.126     brouard  14114:   while (z[0] != 'q') {
1.195     brouard  14115:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14116:     scanf("%s",z);
                   14117:   }
1.283     brouard  14118:   printf("End\n");
1.282     brouard  14119:   exit(0);
1.126     brouard  14120: }

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