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

1.335   ! brouard     1: /* $Id: imach.c,v 1.334 2022/08/25 09:08:41 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.335   ! brouard     4:   Revision 1.334  2022/08/25 09:08:41  brouard
        !             5:   Summary: In progress for quantitative
        !             6: 
1.334     brouard     7:   Revision 1.333  2022/08/21 09:10:30  brouard
                      8:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                      9:   reassigning covariates: my first idea was that people will always
                     10:   use the first covariate V1 into the model but in fact they are
                     11:   producing data with many covariates and can use an equation model
                     12:   with some of the covariate; it means that in a model V2+V3 instead
                     13:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     14:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     15:   the equation model is restricted to two variables only (V2, V3)
                     16:   and the combination for V2 should be codtabm(k,1) instead of
                     17:   (codtabm(k,2), and the code should be
                     18:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     19:   made. All of these should be simplified once a day like we did in
                     20:   hpxij() for example by using precov[nres] which is computed in
                     21:   decoderesult for each nres of each resultline. Loop should be done
                     22:   on the equation model globally by distinguishing only product with
                     23:   age (which are changing with age) and no more on type of
                     24:   covariates, single dummies, single covariates.
                     25: 
1.333     brouard    26:   Revision 1.332  2022/08/21 09:06:25  brouard
                     27:   Summary: Version 0.99r33
                     28: 
                     29:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     30:   reassigning covariates: my first idea was that people will always
                     31:   use the first covariate V1 into the model but in fact they are
                     32:   producing data with many covariates and can use an equation model
                     33:   with some of the covariate; it means that in a model V2+V3 instead
                     34:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     35:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     36:   the equation model is restricted to two variables only (V2, V3)
                     37:   and the combination for V2 should be codtabm(k,1) instead of
                     38:   (codtabm(k,2), and the code should be
                     39:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     40:   made. All of these should be simplified once a day like we did in
                     41:   hpxij() for example by using precov[nres] which is computed in
                     42:   decoderesult for each nres of each resultline. Loop should be done
                     43:   on the equation model globally by distinguishing only product with
                     44:   age (which are changing with age) and no more on type of
                     45:   covariates, single dummies, single covariates.
                     46: 
1.332     brouard    47:   Revision 1.331  2022/08/07 05:40:09  brouard
                     48:   *** empty log message ***
                     49: 
1.331     brouard    50:   Revision 1.330  2022/08/06 07:18:25  brouard
                     51:   Summary: last 0.99r31
                     52: 
                     53:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     54: 
1.330     brouard    55:   Revision 1.329  2022/08/03 17:29:54  brouard
                     56:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     57: 
1.329     brouard    58:   Revision 1.328  2022/07/27 17:40:48  brouard
                     59:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     60: 
1.328     brouard    61:   Revision 1.327  2022/07/27 14:47:35  brouard
                     62:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     63: 
1.327     brouard    64:   Revision 1.326  2022/07/26 17:33:55  brouard
                     65:   Summary: some test with nres=1
                     66: 
1.326     brouard    67:   Revision 1.325  2022/07/25 14:27:23  brouard
                     68:   Summary: r30
                     69: 
                     70:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     71:   coredumped, revealed by Feiuno, thank you.
                     72: 
1.325     brouard    73:   Revision 1.324  2022/07/23 17:44:26  brouard
                     74:   *** empty log message ***
                     75: 
1.324     brouard    76:   Revision 1.323  2022/07/22 12:30:08  brouard
                     77:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     78: 
1.323     brouard    79:   Revision 1.322  2022/07/22 12:27:48  brouard
                     80:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     81: 
1.322     brouard    82:   Revision 1.321  2022/07/22 12:04:24  brouard
                     83:   Summary: r28
                     84: 
                     85:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     86: 
1.321     brouard    87:   Revision 1.320  2022/06/02 05:10:11  brouard
                     88:   *** empty log message ***
                     89: 
1.320     brouard    90:   Revision 1.319  2022/06/02 04:45:11  brouard
                     91:   * imach.c (Module): Adding the Wald tests from the log to the main
                     92:   htm for better display of the maximum likelihood estimators.
                     93: 
1.319     brouard    94:   Revision 1.318  2022/05/24 08:10:59  brouard
                     95:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                     96:   of confidencce intervals with product in the equation modelC
                     97: 
1.318     brouard    98:   Revision 1.317  2022/05/15 15:06:23  brouard
                     99:   * imach.c (Module):  Some minor improvements
                    100: 
1.317     brouard   101:   Revision 1.316  2022/05/11 15:11:31  brouard
                    102:   Summary: r27
                    103: 
1.316     brouard   104:   Revision 1.315  2022/05/11 15:06:32  brouard
                    105:   *** empty log message ***
                    106: 
1.315     brouard   107:   Revision 1.314  2022/04/13 17:43:09  brouard
                    108:   * imach.c (Module): Adding link to text data files
                    109: 
1.314     brouard   110:   Revision 1.313  2022/04/11 15:57:42  brouard
                    111:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    112: 
1.313     brouard   113:   Revision 1.312  2022/04/05 21:24:39  brouard
                    114:   *** empty log message ***
                    115: 
1.312     brouard   116:   Revision 1.311  2022/04/05 21:03:51  brouard
                    117:   Summary: Fixed quantitative covariates
                    118: 
                    119:          Fixed covariates (dummy or quantitative)
                    120:        with missing values have never been allowed but are ERRORS and
                    121:        program quits. Standard deviations of fixed covariates were
                    122:        wrongly computed. Mean and standard deviations of time varying
                    123:        covariates are still not computed.
                    124: 
1.311     brouard   125:   Revision 1.310  2022/03/17 08:45:53  brouard
                    126:   Summary: 99r25
                    127: 
                    128:   Improving detection of errors: result lines should be compatible with
                    129:   the model.
                    130: 
1.310     brouard   131:   Revision 1.309  2021/05/20 12:39:14  brouard
                    132:   Summary: Version 0.99r24
                    133: 
1.309     brouard   134:   Revision 1.308  2021/03/31 13:11:57  brouard
                    135:   Summary: Version 0.99r23
                    136: 
                    137: 
                    138:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    139: 
1.308     brouard   140:   Revision 1.307  2021/03/08 18:11:32  brouard
                    141:   Summary: 0.99r22 fixed bug on result:
                    142: 
1.307     brouard   143:   Revision 1.306  2021/02/20 15:44:02  brouard
                    144:   Summary: Version 0.99r21
                    145: 
                    146:   * imach.c (Module): Fix bug on quitting after result lines!
                    147:   (Module): Version 0.99r21
                    148: 
1.306     brouard   149:   Revision 1.305  2021/02/20 15:28:30  brouard
                    150:   * imach.c (Module): Fix bug on quitting after result lines!
                    151: 
1.305     brouard   152:   Revision 1.304  2021/02/12 11:34:20  brouard
                    153:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    154: 
1.304     brouard   155:   Revision 1.303  2021/02/11 19:50:15  brouard
                    156:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    157: 
1.303     brouard   158:   Revision 1.302  2020/02/22 21:00:05  brouard
                    159:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    160:   and life table from the data without any state)
                    161: 
1.302     brouard   162:   Revision 1.301  2019/06/04 13:51:20  brouard
                    163:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    164: 
1.301     brouard   165:   Revision 1.300  2019/05/22 19:09:45  brouard
                    166:   Summary: version 0.99r19 of May 2019
                    167: 
1.300     brouard   168:   Revision 1.299  2019/05/22 18:37:08  brouard
                    169:   Summary: Cleaned 0.99r19
                    170: 
1.299     brouard   171:   Revision 1.298  2019/05/22 18:19:56  brouard
                    172:   *** empty log message ***
                    173: 
1.298     brouard   174:   Revision 1.297  2019/05/22 17:56:10  brouard
                    175:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    176: 
1.297     brouard   177:   Revision 1.296  2019/05/20 13:03:18  brouard
                    178:   Summary: Projection syntax simplified
                    179: 
                    180: 
                    181:   We can now start projections, forward or backward, from the mean date
                    182:   of inteviews up to or down to a number of years of projection:
                    183:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    184:   or
                    185:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    186:   or
                    187:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    188:   or
                    189:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    190: 
1.296     brouard   191:   Revision 1.295  2019/05/18 09:52:50  brouard
                    192:   Summary: doxygen tex bug
                    193: 
1.295     brouard   194:   Revision 1.294  2019/05/16 14:54:33  brouard
                    195:   Summary: There was some wrong lines added
                    196: 
1.294     brouard   197:   Revision 1.293  2019/05/09 15:17:34  brouard
                    198:   *** empty log message ***
                    199: 
1.293     brouard   200:   Revision 1.292  2019/05/09 14:17:20  brouard
                    201:   Summary: Some updates
                    202: 
1.292     brouard   203:   Revision 1.291  2019/05/09 13:44:18  brouard
                    204:   Summary: Before ncovmax
                    205: 
1.291     brouard   206:   Revision 1.290  2019/05/09 13:39:37  brouard
                    207:   Summary: 0.99r18 unlimited number of individuals
                    208: 
                    209:   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.
                    210: 
1.290     brouard   211:   Revision 1.289  2018/12/13 09:16:26  brouard
                    212:   Summary: Bug for young ages (<-30) will be in r17
                    213: 
1.289     brouard   214:   Revision 1.288  2018/05/02 20:58:27  brouard
                    215:   Summary: Some bugs fixed
                    216: 
1.288     brouard   217:   Revision 1.287  2018/05/01 17:57:25  brouard
                    218:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    219: 
1.287     brouard   220:   Revision 1.286  2018/04/27 14:27:04  brouard
                    221:   Summary: some minor bugs
                    222: 
1.286     brouard   223:   Revision 1.285  2018/04/21 21:02:16  brouard
                    224:   Summary: Some bugs fixed, valgrind tested
                    225: 
1.285     brouard   226:   Revision 1.284  2018/04/20 05:22:13  brouard
                    227:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    228: 
1.284     brouard   229:   Revision 1.283  2018/04/19 14:49:16  brouard
                    230:   Summary: Some minor bugs fixed
                    231: 
1.283     brouard   232:   Revision 1.282  2018/02/27 22:50:02  brouard
                    233:   *** empty log message ***
                    234: 
1.282     brouard   235:   Revision 1.281  2018/02/27 19:25:23  brouard
                    236:   Summary: Adding second argument for quitting
                    237: 
1.281     brouard   238:   Revision 1.280  2018/02/21 07:58:13  brouard
                    239:   Summary: 0.99r15
                    240: 
                    241:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    242: 
1.280     brouard   243:   Revision 1.279  2017/07/20 13:35:01  brouard
                    244:   Summary: temporary working
                    245: 
1.279     brouard   246:   Revision 1.278  2017/07/19 14:09:02  brouard
                    247:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    248: 
1.278     brouard   249:   Revision 1.277  2017/07/17 08:53:49  brouard
                    250:   Summary: BOM files can be read now
                    251: 
1.277     brouard   252:   Revision 1.276  2017/06/30 15:48:31  brouard
                    253:   Summary: Graphs improvements
                    254: 
1.276     brouard   255:   Revision 1.275  2017/06/30 13:39:33  brouard
                    256:   Summary: Saito's color
                    257: 
1.275     brouard   258:   Revision 1.274  2017/06/29 09:47:08  brouard
                    259:   Summary: Version 0.99r14
                    260: 
1.274     brouard   261:   Revision 1.273  2017/06/27 11:06:02  brouard
                    262:   Summary: More documentation on projections
                    263: 
1.273     brouard   264:   Revision 1.272  2017/06/27 10:22:40  brouard
                    265:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    266: 
1.272     brouard   267:   Revision 1.271  2017/06/27 10:17:50  brouard
                    268:   Summary: Some bug with rint
                    269: 
1.271     brouard   270:   Revision 1.270  2017/05/24 05:45:29  brouard
                    271:   *** empty log message ***
                    272: 
1.270     brouard   273:   Revision 1.269  2017/05/23 08:39:25  brouard
                    274:   Summary: Code into subroutine, cleanings
                    275: 
1.269     brouard   276:   Revision 1.268  2017/05/18 20:09:32  brouard
                    277:   Summary: backprojection and confidence intervals of backprevalence
                    278: 
1.268     brouard   279:   Revision 1.267  2017/05/13 10:25:05  brouard
                    280:   Summary: temporary save for backprojection
                    281: 
1.267     brouard   282:   Revision 1.266  2017/05/13 07:26:12  brouard
                    283:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    284: 
1.266     brouard   285:   Revision 1.265  2017/04/26 16:22:11  brouard
                    286:   Summary: imach 0.99r13 Some bugs fixed
                    287: 
1.265     brouard   288:   Revision 1.264  2017/04/26 06:01:29  brouard
                    289:   Summary: Labels in graphs
                    290: 
1.264     brouard   291:   Revision 1.263  2017/04/24 15:23:15  brouard
                    292:   Summary: to save
                    293: 
1.263     brouard   294:   Revision 1.262  2017/04/18 16:48:12  brouard
                    295:   *** empty log message ***
                    296: 
1.262     brouard   297:   Revision 1.261  2017/04/05 10:14:09  brouard
                    298:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    299: 
1.261     brouard   300:   Revision 1.260  2017/04/04 17:46:59  brouard
                    301:   Summary: Gnuplot indexations fixed (humm)
                    302: 
1.260     brouard   303:   Revision 1.259  2017/04/04 13:01:16  brouard
                    304:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    305: 
1.259     brouard   306:   Revision 1.258  2017/04/03 10:17:47  brouard
                    307:   Summary: Version 0.99r12
                    308: 
                    309:   Some cleanings, conformed with updated documentation.
                    310: 
1.258     brouard   311:   Revision 1.257  2017/03/29 16:53:30  brouard
                    312:   Summary: Temp
                    313: 
1.257     brouard   314:   Revision 1.256  2017/03/27 05:50:23  brouard
                    315:   Summary: Temporary
                    316: 
1.256     brouard   317:   Revision 1.255  2017/03/08 16:02:28  brouard
                    318:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    319: 
1.255     brouard   320:   Revision 1.254  2017/03/08 07:13:00  brouard
                    321:   Summary: Fixing data parameter line
                    322: 
1.254     brouard   323:   Revision 1.253  2016/12/15 11:59:41  brouard
                    324:   Summary: 0.99 in progress
                    325: 
1.253     brouard   326:   Revision 1.252  2016/09/15 21:15:37  brouard
                    327:   *** empty log message ***
                    328: 
1.252     brouard   329:   Revision 1.251  2016/09/15 15:01:13  brouard
                    330:   Summary: not working
                    331: 
1.251     brouard   332:   Revision 1.250  2016/09/08 16:07:27  brouard
                    333:   Summary: continue
                    334: 
1.250     brouard   335:   Revision 1.249  2016/09/07 17:14:18  brouard
                    336:   Summary: Starting values from frequencies
                    337: 
1.249     brouard   338:   Revision 1.248  2016/09/07 14:10:18  brouard
                    339:   *** empty log message ***
                    340: 
1.248     brouard   341:   Revision 1.247  2016/09/02 11:11:21  brouard
                    342:   *** empty log message ***
                    343: 
1.247     brouard   344:   Revision 1.246  2016/09/02 08:49:22  brouard
                    345:   *** empty log message ***
                    346: 
1.246     brouard   347:   Revision 1.245  2016/09/02 07:25:01  brouard
                    348:   *** empty log message ***
                    349: 
1.245     brouard   350:   Revision 1.244  2016/09/02 07:17:34  brouard
                    351:   *** empty log message ***
                    352: 
1.244     brouard   353:   Revision 1.243  2016/09/02 06:45:35  brouard
                    354:   *** empty log message ***
                    355: 
1.243     brouard   356:   Revision 1.242  2016/08/30 15:01:20  brouard
                    357:   Summary: Fixing a lots
                    358: 
1.242     brouard   359:   Revision 1.241  2016/08/29 17:17:25  brouard
                    360:   Summary: gnuplot problem in Back projection to fix
                    361: 
1.241     brouard   362:   Revision 1.240  2016/08/29 07:53:18  brouard
                    363:   Summary: Better
                    364: 
1.240     brouard   365:   Revision 1.239  2016/08/26 15:51:03  brouard
                    366:   Summary: Improvement in Powell output in order to copy and paste
                    367: 
                    368:   Author:
                    369: 
1.239     brouard   370:   Revision 1.238  2016/08/26 14:23:35  brouard
                    371:   Summary: Starting tests of 0.99
                    372: 
1.238     brouard   373:   Revision 1.237  2016/08/26 09:20:19  brouard
                    374:   Summary: to valgrind
                    375: 
1.237     brouard   376:   Revision 1.236  2016/08/25 10:50:18  brouard
                    377:   *** empty log message ***
                    378: 
1.236     brouard   379:   Revision 1.235  2016/08/25 06:59:23  brouard
                    380:   *** empty log message ***
                    381: 
1.235     brouard   382:   Revision 1.234  2016/08/23 16:51:20  brouard
                    383:   *** empty log message ***
                    384: 
1.234     brouard   385:   Revision 1.233  2016/08/23 07:40:50  brouard
                    386:   Summary: not working
                    387: 
1.233     brouard   388:   Revision 1.232  2016/08/22 14:20:21  brouard
                    389:   Summary: not working
                    390: 
1.232     brouard   391:   Revision 1.231  2016/08/22 07:17:15  brouard
                    392:   Summary: not working
                    393: 
1.231     brouard   394:   Revision 1.230  2016/08/22 06:55:53  brouard
                    395:   Summary: Not working
                    396: 
1.230     brouard   397:   Revision 1.229  2016/07/23 09:45:53  brouard
                    398:   Summary: Completing for func too
                    399: 
1.229     brouard   400:   Revision 1.228  2016/07/22 17:45:30  brouard
                    401:   Summary: Fixing some arrays, still debugging
                    402: 
1.227     brouard   403:   Revision 1.226  2016/07/12 18:42:34  brouard
                    404:   Summary: temp
                    405: 
1.226     brouard   406:   Revision 1.225  2016/07/12 08:40:03  brouard
                    407:   Summary: saving but not running
                    408: 
1.225     brouard   409:   Revision 1.224  2016/07/01 13:16:01  brouard
                    410:   Summary: Fixes
                    411: 
1.224     brouard   412:   Revision 1.223  2016/02/19 09:23:35  brouard
                    413:   Summary: temporary
                    414: 
1.223     brouard   415:   Revision 1.222  2016/02/17 08:14:50  brouard
                    416:   Summary: Probably last 0.98 stable version 0.98r6
                    417: 
1.222     brouard   418:   Revision 1.221  2016/02/15 23:35:36  brouard
                    419:   Summary: minor bug
                    420: 
1.220     brouard   421:   Revision 1.219  2016/02/15 00:48:12  brouard
                    422:   *** empty log message ***
                    423: 
1.219     brouard   424:   Revision 1.218  2016/02/12 11:29:23  brouard
                    425:   Summary: 0.99 Back projections
                    426: 
1.218     brouard   427:   Revision 1.217  2015/12/23 17:18:31  brouard
                    428:   Summary: Experimental backcast
                    429: 
1.217     brouard   430:   Revision 1.216  2015/12/18 17:32:11  brouard
                    431:   Summary: 0.98r4 Warning and status=-2
                    432: 
                    433:   Version 0.98r4 is now:
                    434:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    435:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    436:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    437: 
1.216     brouard   438:   Revision 1.215  2015/12/16 08:52:24  brouard
                    439:   Summary: 0.98r4 working
                    440: 
1.215     brouard   441:   Revision 1.214  2015/12/16 06:57:54  brouard
                    442:   Summary: temporary not working
                    443: 
1.214     brouard   444:   Revision 1.213  2015/12/11 18:22:17  brouard
                    445:   Summary: 0.98r4
                    446: 
1.213     brouard   447:   Revision 1.212  2015/11/21 12:47:24  brouard
                    448:   Summary: minor typo
                    449: 
1.212     brouard   450:   Revision 1.211  2015/11/21 12:41:11  brouard
                    451:   Summary: 0.98r3 with some graph of projected cross-sectional
                    452: 
                    453:   Author: Nicolas Brouard
                    454: 
1.211     brouard   455:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   456:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   457:   Summary: Adding ftolpl parameter
                    458:   Author: N Brouard
                    459: 
                    460:   We had difficulties to get smoothed confidence intervals. It was due
                    461:   to the period prevalence which wasn't computed accurately. The inner
                    462:   parameter ftolpl is now an outer parameter of the .imach parameter
                    463:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    464:   computation are long.
                    465: 
1.209     brouard   466:   Revision 1.208  2015/11/17 14:31:57  brouard
                    467:   Summary: temporary
                    468: 
1.208     brouard   469:   Revision 1.207  2015/10/27 17:36:57  brouard
                    470:   *** empty log message ***
                    471: 
1.207     brouard   472:   Revision 1.206  2015/10/24 07:14:11  brouard
                    473:   *** empty log message ***
                    474: 
1.206     brouard   475:   Revision 1.205  2015/10/23 15:50:53  brouard
                    476:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    477: 
1.205     brouard   478:   Revision 1.204  2015/10/01 16:20:26  brouard
                    479:   Summary: Some new graphs of contribution to likelihood
                    480: 
1.204     brouard   481:   Revision 1.203  2015/09/30 17:45:14  brouard
                    482:   Summary: looking at better estimation of the hessian
                    483: 
                    484:   Also a better criteria for convergence to the period prevalence And
                    485:   therefore adding the number of years needed to converge. (The
                    486:   prevalence in any alive state shold sum to one
                    487: 
1.203     brouard   488:   Revision 1.202  2015/09/22 19:45:16  brouard
                    489:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    490: 
1.202     brouard   491:   Revision 1.201  2015/09/15 17:34:58  brouard
                    492:   Summary: 0.98r0
                    493: 
                    494:   - Some new graphs like suvival functions
                    495:   - Some bugs fixed like model=1+age+V2.
                    496: 
1.201     brouard   497:   Revision 1.200  2015/09/09 16:53:55  brouard
                    498:   Summary: Big bug thanks to Flavia
                    499: 
                    500:   Even model=1+age+V2. did not work anymore
                    501: 
1.200     brouard   502:   Revision 1.199  2015/09/07 14:09:23  brouard
                    503:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    504: 
1.199     brouard   505:   Revision 1.198  2015/09/03 07:14:39  brouard
                    506:   Summary: 0.98q5 Flavia
                    507: 
1.198     brouard   508:   Revision 1.197  2015/09/01 18:24:39  brouard
                    509:   *** empty log message ***
                    510: 
1.197     brouard   511:   Revision 1.196  2015/08/18 23:17:52  brouard
                    512:   Summary: 0.98q5
                    513: 
1.196     brouard   514:   Revision 1.195  2015/08/18 16:28:39  brouard
                    515:   Summary: Adding a hack for testing purpose
                    516: 
                    517:   After reading the title, ftol and model lines, if the comment line has
                    518:   a q, starting with #q, the answer at the end of the run is quit. It
                    519:   permits to run test files in batch with ctest. The former workaround was
                    520:   $ echo q | imach foo.imach
                    521: 
1.195     brouard   522:   Revision 1.194  2015/08/18 13:32:00  brouard
                    523:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    524: 
1.194     brouard   525:   Revision 1.193  2015/08/04 07:17:42  brouard
                    526:   Summary: 0.98q4
                    527: 
1.193     brouard   528:   Revision 1.192  2015/07/16 16:49:02  brouard
                    529:   Summary: Fixing some outputs
                    530: 
1.192     brouard   531:   Revision 1.191  2015/07/14 10:00:33  brouard
                    532:   Summary: Some fixes
                    533: 
1.191     brouard   534:   Revision 1.190  2015/05/05 08:51:13  brouard
                    535:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    536: 
                    537:   Fix 1+age+.
                    538: 
1.190     brouard   539:   Revision 1.189  2015/04/30 14:45:16  brouard
                    540:   Summary: 0.98q2
                    541: 
1.189     brouard   542:   Revision 1.188  2015/04/30 08:27:53  brouard
                    543:   *** empty log message ***
                    544: 
1.188     brouard   545:   Revision 1.187  2015/04/29 09:11:15  brouard
                    546:   *** empty log message ***
                    547: 
1.187     brouard   548:   Revision 1.186  2015/04/23 12:01:52  brouard
                    549:   Summary: V1*age is working now, version 0.98q1
                    550: 
                    551:   Some codes had been disabled in order to simplify and Vn*age was
                    552:   working in the optimization phase, ie, giving correct MLE parameters,
                    553:   but, as usual, outputs were not correct and program core dumped.
                    554: 
1.186     brouard   555:   Revision 1.185  2015/03/11 13:26:42  brouard
                    556:   Summary: Inclusion of compile and links command line for Intel Compiler
                    557: 
1.185     brouard   558:   Revision 1.184  2015/03/11 11:52:39  brouard
                    559:   Summary: Back from Windows 8. Intel Compiler
                    560: 
1.184     brouard   561:   Revision 1.183  2015/03/10 20:34:32  brouard
                    562:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    563: 
                    564:   We use directest instead of original Powell test; probably no
                    565:   incidence on the results, but better justifications;
                    566:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    567:   wrong results.
                    568: 
1.183     brouard   569:   Revision 1.182  2015/02/12 08:19:57  brouard
                    570:   Summary: Trying to keep directest which seems simpler and more general
                    571:   Author: Nicolas Brouard
                    572: 
1.182     brouard   573:   Revision 1.181  2015/02/11 23:22:24  brouard
                    574:   Summary: Comments on Powell added
                    575: 
                    576:   Author:
                    577: 
1.181     brouard   578:   Revision 1.180  2015/02/11 17:33:45  brouard
                    579:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    580: 
1.180     brouard   581:   Revision 1.179  2015/01/04 09:57:06  brouard
                    582:   Summary: back to OS/X
                    583: 
1.179     brouard   584:   Revision 1.178  2015/01/04 09:35:48  brouard
                    585:   *** empty log message ***
                    586: 
1.178     brouard   587:   Revision 1.177  2015/01/03 18:40:56  brouard
                    588:   Summary: Still testing ilc32 on OSX
                    589: 
1.177     brouard   590:   Revision 1.176  2015/01/03 16:45:04  brouard
                    591:   *** empty log message ***
                    592: 
1.176     brouard   593:   Revision 1.175  2015/01/03 16:33:42  brouard
                    594:   *** empty log message ***
                    595: 
1.175     brouard   596:   Revision 1.174  2015/01/03 16:15:49  brouard
                    597:   Summary: Still in cross-compilation
                    598: 
1.174     brouard   599:   Revision 1.173  2015/01/03 12:06:26  brouard
                    600:   Summary: trying to detect cross-compilation
                    601: 
1.173     brouard   602:   Revision 1.172  2014/12/27 12:07:47  brouard
                    603:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    604: 
1.172     brouard   605:   Revision 1.171  2014/12/23 13:26:59  brouard
                    606:   Summary: Back from Visual C
                    607: 
                    608:   Still problem with utsname.h on Windows
                    609: 
1.171     brouard   610:   Revision 1.170  2014/12/23 11:17:12  brouard
                    611:   Summary: Cleaning some \%% back to %%
                    612: 
                    613:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    614: 
1.170     brouard   615:   Revision 1.169  2014/12/22 23:08:31  brouard
                    616:   Summary: 0.98p
                    617: 
                    618:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    619: 
1.169     brouard   620:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   621:   Summary: update
1.169     brouard   622: 
1.168     brouard   623:   Revision 1.167  2014/12/22 13:50:56  brouard
                    624:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    625: 
                    626:   Testing on Linux 64
                    627: 
1.167     brouard   628:   Revision 1.166  2014/12/22 11:40:47  brouard
                    629:   *** empty log message ***
                    630: 
1.166     brouard   631:   Revision 1.165  2014/12/16 11:20:36  brouard
                    632:   Summary: After compiling on Visual C
                    633: 
                    634:   * imach.c (Module): Merging 1.61 to 1.162
                    635: 
1.165     brouard   636:   Revision 1.164  2014/12/16 10:52:11  brouard
                    637:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    638: 
                    639:   * imach.c (Module): Merging 1.61 to 1.162
                    640: 
1.164     brouard   641:   Revision 1.163  2014/12/16 10:30:11  brouard
                    642:   * imach.c (Module): Merging 1.61 to 1.162
                    643: 
1.163     brouard   644:   Revision 1.162  2014/09/25 11:43:39  brouard
                    645:   Summary: temporary backup 0.99!
                    646: 
1.162     brouard   647:   Revision 1.1  2014/09/16 11:06:58  brouard
                    648:   Summary: With some code (wrong) for nlopt
                    649: 
                    650:   Author:
                    651: 
                    652:   Revision 1.161  2014/09/15 20:41:41  brouard
                    653:   Summary: Problem with macro SQR on Intel compiler
                    654: 
1.161     brouard   655:   Revision 1.160  2014/09/02 09:24:05  brouard
                    656:   *** empty log message ***
                    657: 
1.160     brouard   658:   Revision 1.159  2014/09/01 10:34:10  brouard
                    659:   Summary: WIN32
                    660:   Author: Brouard
                    661: 
1.159     brouard   662:   Revision 1.158  2014/08/27 17:11:51  brouard
                    663:   *** empty log message ***
                    664: 
1.158     brouard   665:   Revision 1.157  2014/08/27 16:26:55  brouard
                    666:   Summary: Preparing windows Visual studio version
                    667:   Author: Brouard
                    668: 
                    669:   In order to compile on Visual studio, time.h is now correct and time_t
                    670:   and tm struct should be used. difftime should be used but sometimes I
                    671:   just make the differences in raw time format (time(&now).
                    672:   Trying to suppress #ifdef LINUX
                    673:   Add xdg-open for __linux in order to open default browser.
                    674: 
1.157     brouard   675:   Revision 1.156  2014/08/25 20:10:10  brouard
                    676:   *** empty log message ***
                    677: 
1.156     brouard   678:   Revision 1.155  2014/08/25 18:32:34  brouard
                    679:   Summary: New compile, minor changes
                    680:   Author: Brouard
                    681: 
1.155     brouard   682:   Revision 1.154  2014/06/20 17:32:08  brouard
                    683:   Summary: Outputs now all graphs of convergence to period prevalence
                    684: 
1.154     brouard   685:   Revision 1.153  2014/06/20 16:45:46  brouard
                    686:   Summary: If 3 live state, convergence to period prevalence on same graph
                    687:   Author: Brouard
                    688: 
1.153     brouard   689:   Revision 1.152  2014/06/18 17:54:09  brouard
                    690:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    691: 
1.152     brouard   692:   Revision 1.151  2014/06/18 16:43:30  brouard
                    693:   *** empty log message ***
                    694: 
1.151     brouard   695:   Revision 1.150  2014/06/18 16:42:35  brouard
                    696:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    697:   Author: brouard
                    698: 
1.150     brouard   699:   Revision 1.149  2014/06/18 15:51:14  brouard
                    700:   Summary: Some fixes in parameter files errors
                    701:   Author: Nicolas Brouard
                    702: 
1.149     brouard   703:   Revision 1.148  2014/06/17 17:38:48  brouard
                    704:   Summary: Nothing new
                    705:   Author: Brouard
                    706: 
                    707:   Just a new packaging for OS/X version 0.98nS
                    708: 
1.148     brouard   709:   Revision 1.147  2014/06/16 10:33:11  brouard
                    710:   *** empty log message ***
                    711: 
1.147     brouard   712:   Revision 1.146  2014/06/16 10:20:28  brouard
                    713:   Summary: Merge
                    714:   Author: Brouard
                    715: 
                    716:   Merge, before building revised version.
                    717: 
1.146     brouard   718:   Revision 1.145  2014/06/10 21:23:15  brouard
                    719:   Summary: Debugging with valgrind
                    720:   Author: Nicolas Brouard
                    721: 
                    722:   Lot of changes in order to output the results with some covariates
                    723:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    724:   improve the code.
                    725:   No more memory valgrind error but a lot has to be done in order to
                    726:   continue the work of splitting the code into subroutines.
                    727:   Also, decodemodel has been improved. Tricode is still not
                    728:   optimal. nbcode should be improved. Documentation has been added in
                    729:   the source code.
                    730: 
1.144     brouard   731:   Revision 1.143  2014/01/26 09:45:38  brouard
                    732:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    733: 
                    734:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    735:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    736: 
1.143     brouard   737:   Revision 1.142  2014/01/26 03:57:36  brouard
                    738:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    739: 
                    740:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    741: 
1.142     brouard   742:   Revision 1.141  2014/01/26 02:42:01  brouard
                    743:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    744: 
1.141     brouard   745:   Revision 1.140  2011/09/02 10:37:54  brouard
                    746:   Summary: times.h is ok with mingw32 now.
                    747: 
1.140     brouard   748:   Revision 1.139  2010/06/14 07:50:17  brouard
                    749:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    750:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    751: 
1.139     brouard   752:   Revision 1.138  2010/04/30 18:19:40  brouard
                    753:   *** empty log message ***
                    754: 
1.138     brouard   755:   Revision 1.137  2010/04/29 18:11:38  brouard
                    756:   (Module): Checking covariates for more complex models
                    757:   than V1+V2. A lot of change to be done. Unstable.
                    758: 
1.137     brouard   759:   Revision 1.136  2010/04/26 20:30:53  brouard
                    760:   (Module): merging some libgsl code. Fixing computation
                    761:   of likelione (using inter/intrapolation if mle = 0) in order to
                    762:   get same likelihood as if mle=1.
                    763:   Some cleaning of code and comments added.
                    764: 
1.136     brouard   765:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   768:   Revision 1.134  2009/10/29 13:18:53  brouard
                    769:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    770: 
1.134     brouard   771:   Revision 1.133  2009/07/06 10:21:25  brouard
                    772:   just nforces
                    773: 
1.133     brouard   774:   Revision 1.132  2009/07/06 08:22:05  brouard
                    775:   Many tings
                    776: 
1.132     brouard   777:   Revision 1.131  2009/06/20 16:22:47  brouard
                    778:   Some dimensions resccaled
                    779: 
1.131     brouard   780:   Revision 1.130  2009/05/26 06:44:34  brouard
                    781:   (Module): Max Covariate is now set to 20 instead of 8. A
                    782:   lot of cleaning with variables initialized to 0. Trying to make
                    783:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    784: 
1.130     brouard   785:   Revision 1.129  2007/08/31 13:49:27  lievre
                    786:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    787: 
1.129     lievre    788:   Revision 1.128  2006/06/30 13:02:05  brouard
                    789:   (Module): Clarifications on computing e.j
                    790: 
1.128     brouard   791:   Revision 1.127  2006/04/28 18:11:50  brouard
                    792:   (Module): Yes the sum of survivors was wrong since
                    793:   imach-114 because nhstepm was no more computed in the age
                    794:   loop. Now we define nhstepma in the age loop.
                    795:   (Module): In order to speed up (in case of numerous covariates) we
                    796:   compute health expectancies (without variances) in a first step
                    797:   and then all the health expectancies with variances or standard
                    798:   deviation (needs data from the Hessian matrices) which slows the
                    799:   computation.
                    800:   In the future we should be able to stop the program is only health
                    801:   expectancies and graph are needed without standard deviations.
                    802: 
1.127     brouard   803:   Revision 1.126  2006/04/28 17:23:28  brouard
                    804:   (Module): Yes the sum of survivors was wrong since
                    805:   imach-114 because nhstepm was no more computed in the age
                    806:   loop. Now we define nhstepma in the age loop.
                    807:   Version 0.98h
                    808: 
1.126     brouard   809:   Revision 1.125  2006/04/04 15:20:31  lievre
                    810:   Errors in calculation of health expectancies. Age was not initialized.
                    811:   Forecasting file added.
                    812: 
                    813:   Revision 1.124  2006/03/22 17:13:53  lievre
                    814:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    815:   The log-likelihood is printed in the log file
                    816: 
                    817:   Revision 1.123  2006/03/20 10:52:43  brouard
                    818:   * imach.c (Module): <title> changed, corresponds to .htm file
                    819:   name. <head> headers where missing.
                    820: 
                    821:   * imach.c (Module): Weights can have a decimal point as for
                    822:   English (a comma might work with a correct LC_NUMERIC environment,
                    823:   otherwise the weight is truncated).
                    824:   Modification of warning when the covariates values are not 0 or
                    825:   1.
                    826:   Version 0.98g
                    827: 
                    828:   Revision 1.122  2006/03/20 09:45:41  brouard
                    829:   (Module): Weights can have a decimal point as for
                    830:   English (a comma might work with a correct LC_NUMERIC environment,
                    831:   otherwise the weight is truncated).
                    832:   Modification of warning when the covariates values are not 0 or
                    833:   1.
                    834:   Version 0.98g
                    835: 
                    836:   Revision 1.121  2006/03/16 17:45:01  lievre
                    837:   * imach.c (Module): Comments concerning covariates added
                    838: 
                    839:   * imach.c (Module): refinements in the computation of lli if
                    840:   status=-2 in order to have more reliable computation if stepm is
                    841:   not 1 month. Version 0.98f
                    842: 
                    843:   Revision 1.120  2006/03/16 15:10:38  lievre
                    844:   (Module): refinements in the computation of lli if
                    845:   status=-2 in order to have more reliable computation if stepm is
                    846:   not 1 month. Version 0.98f
                    847: 
                    848:   Revision 1.119  2006/03/15 17:42:26  brouard
                    849:   (Module): Bug if status = -2, the loglikelihood was
                    850:   computed as likelihood omitting the logarithm. Version O.98e
                    851: 
                    852:   Revision 1.118  2006/03/14 18:20:07  brouard
                    853:   (Module): varevsij Comments added explaining the second
                    854:   table of variances if popbased=1 .
                    855:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    856:   (Module): Function pstamp added
                    857:   (Module): Version 0.98d
                    858: 
                    859:   Revision 1.117  2006/03/14 17:16:22  brouard
                    860:   (Module): varevsij Comments added explaining the second
                    861:   table of variances if popbased=1 .
                    862:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    863:   (Module): Function pstamp added
                    864:   (Module): Version 0.98d
                    865: 
                    866:   Revision 1.116  2006/03/06 10:29:27  brouard
                    867:   (Module): Variance-covariance wrong links and
                    868:   varian-covariance of ej. is needed (Saito).
                    869: 
                    870:   Revision 1.115  2006/02/27 12:17:45  brouard
                    871:   (Module): One freematrix added in mlikeli! 0.98c
                    872: 
                    873:   Revision 1.114  2006/02/26 12:57:58  brouard
                    874:   (Module): Some improvements in processing parameter
                    875:   filename with strsep.
                    876: 
                    877:   Revision 1.113  2006/02/24 14:20:24  brouard
                    878:   (Module): Memory leaks checks with valgrind and:
                    879:   datafile was not closed, some imatrix were not freed and on matrix
                    880:   allocation too.
                    881: 
                    882:   Revision 1.112  2006/01/30 09:55:26  brouard
                    883:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    884: 
                    885:   Revision 1.111  2006/01/25 20:38:18  brouard
                    886:   (Module): Lots of cleaning and bugs added (Gompertz)
                    887:   (Module): Comments can be added in data file. Missing date values
                    888:   can be a simple dot '.'.
                    889: 
                    890:   Revision 1.110  2006/01/25 00:51:50  brouard
                    891:   (Module): Lots of cleaning and bugs added (Gompertz)
                    892: 
                    893:   Revision 1.109  2006/01/24 19:37:15  brouard
                    894:   (Module): Comments (lines starting with a #) are allowed in data.
                    895: 
                    896:   Revision 1.108  2006/01/19 18:05:42  lievre
                    897:   Gnuplot problem appeared...
                    898:   To be fixed
                    899: 
                    900:   Revision 1.107  2006/01/19 16:20:37  brouard
                    901:   Test existence of gnuplot in imach path
                    902: 
                    903:   Revision 1.106  2006/01/19 13:24:36  brouard
                    904:   Some cleaning and links added in html output
                    905: 
                    906:   Revision 1.105  2006/01/05 20:23:19  lievre
                    907:   *** empty log message ***
                    908: 
                    909:   Revision 1.104  2005/09/30 16:11:43  lievre
                    910:   (Module): sump fixed, loop imx fixed, and simplifications.
                    911:   (Module): If the status is missing at the last wave but we know
                    912:   that the person is alive, then we can code his/her status as -2
                    913:   (instead of missing=-1 in earlier versions) and his/her
                    914:   contributions to the likelihood is 1 - Prob of dying from last
                    915:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    916:   the healthy state at last known wave). Version is 0.98
                    917: 
                    918:   Revision 1.103  2005/09/30 15:54:49  lievre
                    919:   (Module): sump fixed, loop imx fixed, and simplifications.
                    920: 
                    921:   Revision 1.102  2004/09/15 17:31:30  brouard
                    922:   Add the possibility to read data file including tab characters.
                    923: 
                    924:   Revision 1.101  2004/09/15 10:38:38  brouard
                    925:   Fix on curr_time
                    926: 
                    927:   Revision 1.100  2004/07/12 18:29:06  brouard
                    928:   Add version for Mac OS X. Just define UNIX in Makefile
                    929: 
                    930:   Revision 1.99  2004/06/05 08:57:40  brouard
                    931:   *** empty log message ***
                    932: 
                    933:   Revision 1.98  2004/05/16 15:05:56  brouard
                    934:   New version 0.97 . First attempt to estimate force of mortality
                    935:   directly from the data i.e. without the need of knowing the health
                    936:   state at each age, but using a Gompertz model: log u =a + b*age .
                    937:   This is the basic analysis of mortality and should be done before any
                    938:   other analysis, in order to test if the mortality estimated from the
                    939:   cross-longitudinal survey is different from the mortality estimated
                    940:   from other sources like vital statistic data.
                    941: 
                    942:   The same imach parameter file can be used but the option for mle should be -3.
                    943: 
1.324     brouard   944:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   945:   former routines in order to include the new code within the former code.
                    946: 
                    947:   The output is very simple: only an estimate of the intercept and of
                    948:   the slope with 95% confident intervals.
                    949: 
                    950:   Current limitations:
                    951:   A) Even if you enter covariates, i.e. with the
                    952:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    953:   B) There is no computation of Life Expectancy nor Life Table.
                    954: 
                    955:   Revision 1.97  2004/02/20 13:25:42  lievre
                    956:   Version 0.96d. Population forecasting command line is (temporarily)
                    957:   suppressed.
                    958: 
                    959:   Revision 1.96  2003/07/15 15:38:55  brouard
                    960:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    961:   rewritten within the same printf. Workaround: many printfs.
                    962: 
                    963:   Revision 1.95  2003/07/08 07:54:34  brouard
                    964:   * imach.c (Repository):
                    965:   (Repository): Using imachwizard code to output a more meaningful covariance
                    966:   matrix (cov(a12,c31) instead of numbers.
                    967: 
                    968:   Revision 1.94  2003/06/27 13:00:02  brouard
                    969:   Just cleaning
                    970: 
                    971:   Revision 1.93  2003/06/25 16:33:55  brouard
                    972:   (Module): On windows (cygwin) function asctime_r doesn't
                    973:   exist so I changed back to asctime which exists.
                    974:   (Module): Version 0.96b
                    975: 
                    976:   Revision 1.92  2003/06/25 16:30:45  brouard
                    977:   (Module): On windows (cygwin) function asctime_r doesn't
                    978:   exist so I changed back to asctime which exists.
                    979: 
                    980:   Revision 1.91  2003/06/25 15:30:29  brouard
                    981:   * imach.c (Repository): Duplicated warning errors corrected.
                    982:   (Repository): Elapsed time after each iteration is now output. It
                    983:   helps to forecast when convergence will be reached. Elapsed time
                    984:   is stamped in powell.  We created a new html file for the graphs
                    985:   concerning matrix of covariance. It has extension -cov.htm.
                    986: 
                    987:   Revision 1.90  2003/06/24 12:34:15  brouard
                    988:   (Module): Some bugs corrected for windows. Also, when
                    989:   mle=-1 a template is output in file "or"mypar.txt with the design
                    990:   of the covariance matrix to be input.
                    991: 
                    992:   Revision 1.89  2003/06/24 12:30:52  brouard
                    993:   (Module): Some bugs corrected for windows. Also, when
                    994:   mle=-1 a template is output in file "or"mypar.txt with the design
                    995:   of the covariance matrix to be input.
                    996: 
                    997:   Revision 1.88  2003/06/23 17:54:56  brouard
                    998:   * 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.
                    999: 
                   1000:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1001:   Version 0.96
                   1002: 
                   1003:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1004:   (Module): Change position of html and gnuplot routines and added
                   1005:   routine fileappend.
                   1006: 
                   1007:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1008:   * imach.c (Repository): Check when date of death was earlier that
                   1009:   current date of interview. It may happen when the death was just
                   1010:   prior to the death. In this case, dh was negative and likelihood
                   1011:   was wrong (infinity). We still send an "Error" but patch by
                   1012:   assuming that the date of death was just one stepm after the
                   1013:   interview.
                   1014:   (Repository): Because some people have very long ID (first column)
                   1015:   we changed int to long in num[] and we added a new lvector for
                   1016:   memory allocation. But we also truncated to 8 characters (left
                   1017:   truncation)
                   1018:   (Repository): No more line truncation errors.
                   1019: 
                   1020:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1021:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1022:   place. It differs from routine "prevalence" which may be called
                   1023:   many times. Probs is memory consuming and must be used with
                   1024:   parcimony.
                   1025:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1026: 
                   1027:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1028:   *** empty log message ***
                   1029: 
                   1030:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1031:   Add log in  imach.c and  fullversion number is now printed.
                   1032: 
                   1033: */
                   1034: /*
                   1035:    Interpolated Markov Chain
                   1036: 
                   1037:   Short summary of the programme:
                   1038:   
1.227     brouard  1039:   This program computes Healthy Life Expectancies or State-specific
                   1040:   (if states aren't health statuses) Expectancies from
                   1041:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1042: 
                   1043:   -1- a first survey ("cross") where individuals from different ages
                   1044:   are interviewed on their health status or degree of disability (in
                   1045:   the case of a health survey which is our main interest)
                   1046: 
                   1047:   -2- at least a second wave of interviews ("longitudinal") which
                   1048:   measure each change (if any) in individual health status.  Health
                   1049:   expectancies are computed from the time spent in each health state
                   1050:   according to a model. More health states you consider, more time is
                   1051:   necessary to reach the Maximum Likelihood of the parameters involved
                   1052:   in the model.  The simplest model is the multinomial logistic model
                   1053:   where pij is the probability to be observed in state j at the second
                   1054:   wave conditional to be observed in state i at the first
                   1055:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1056:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1057:   have a more complex model than "constant and age", you should modify
                   1058:   the program where the markup *Covariates have to be included here
                   1059:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1060:   convergence.
                   1061: 
                   1062:   The advantage of this computer programme, compared to a simple
                   1063:   multinomial logistic model, is clear when the delay between waves is not
                   1064:   identical for each individual. Also, if a individual missed an
                   1065:   intermediate interview, the information is lost, but taken into
                   1066:   account using an interpolation or extrapolation.  
                   1067: 
                   1068:   hPijx is the probability to be observed in state i at age x+h
                   1069:   conditional to the observed state i at age x. The delay 'h' can be
                   1070:   split into an exact number (nh*stepm) of unobserved intermediate
                   1071:   states. This elementary transition (by month, quarter,
                   1072:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1073:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1074:   and the contribution of each individual to the likelihood is simply
                   1075:   hPijx.
                   1076: 
                   1077:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1078:   of the life expectancies. It also computes the period (stable) prevalence.
                   1079: 
                   1080: Back prevalence and projections:
1.227     brouard  1081: 
                   1082:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1083:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1084:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1085:    mobilavproj)
                   1086: 
                   1087:     Computes the back prevalence limit for any combination of
                   1088:     covariate values k at any age between ageminpar and agemaxpar and
                   1089:     returns it in **bprlim. In the loops,
                   1090: 
                   1091:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1092:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1093: 
                   1094:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1095:    Computes for any combination of covariates k and any age between bage and fage 
                   1096:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1097:                        oldm=oldms;savm=savms;
1.227     brouard  1098: 
1.267     brouard  1099:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1100:      Computes the transition matrix starting at age 'age' over
                   1101:      'nhstepm*hstepm*stepm' months (i.e. until
                   1102:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1103:      nhstepm*hstepm matrices. 
                   1104: 
                   1105:      Returns p3mat[i][j][h] after calling
                   1106:      p3mat[i][j][h]=matprod2(newm,
                   1107:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1108:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1109:      oldm);
1.226     brouard  1110: 
                   1111: Important routines
                   1112: 
                   1113: - func (or funcone), computes logit (pij) distinguishing
                   1114:   o fixed variables (single or product dummies or quantitative);
                   1115:   o varying variables by:
                   1116:    (1) wave (single, product dummies, quantitative), 
                   1117:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1118:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1119:        % varying dummy (not done) or quantitative (not done);
                   1120: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1121:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1122: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1123:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1124:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1125: 
1.226     brouard  1126: 
                   1127:   
1.324     brouard  1128:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1129:            Institut national d'études démographiques, Paris.
1.126     brouard  1130:   This software have been partly granted by Euro-REVES, a concerted action
                   1131:   from the European Union.
                   1132:   It is copyrighted identically to a GNU software product, ie programme and
                   1133:   software can be distributed freely for non commercial use. Latest version
                   1134:   can be accessed at http://euroreves.ined.fr/imach .
                   1135: 
                   1136:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1137:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1138:   
                   1139:   **********************************************************************/
                   1140: /*
                   1141:   main
                   1142:   read parameterfile
                   1143:   read datafile
                   1144:   concatwav
                   1145:   freqsummary
                   1146:   if (mle >= 1)
                   1147:     mlikeli
                   1148:   print results files
                   1149:   if mle==1 
                   1150:      computes hessian
                   1151:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1152:       begin-prev-date,...
                   1153:   open gnuplot file
                   1154:   open html file
1.145     brouard  1155:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1156:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1157:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1158:     freexexit2 possible for memory heap.
                   1159: 
                   1160:   h Pij x                         | pij_nom  ficrestpij
                   1161:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1162:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1163:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1164: 
                   1165:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1166:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1167:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1168:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1169:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1170: 
1.126     brouard  1171:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1172:   health expectancies
                   1173:   Variance-covariance of DFLE
                   1174:   prevalence()
                   1175:    movingaverage()
                   1176:   varevsij() 
                   1177:   if popbased==1 varevsij(,popbased)
                   1178:   total life expectancies
                   1179:   Variance of period (stable) prevalence
                   1180:  end
                   1181: */
                   1182: 
1.187     brouard  1183: /* #define DEBUG */
                   1184: /* #define DEBUGBRENT */
1.203     brouard  1185: /* #define DEBUGLINMIN */
                   1186: /* #define DEBUGHESS */
                   1187: #define DEBUGHESSIJ
1.224     brouard  1188: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1189: #define POWELL /* Instead of NLOPT */
1.224     brouard  1190: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1191: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1192: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1193: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1194: 
                   1195: #include <math.h>
                   1196: #include <stdio.h>
                   1197: #include <stdlib.h>
                   1198: #include <string.h>
1.226     brouard  1199: #include <ctype.h>
1.159     brouard  1200: 
                   1201: #ifdef _WIN32
                   1202: #include <io.h>
1.172     brouard  1203: #include <windows.h>
                   1204: #include <tchar.h>
1.159     brouard  1205: #else
1.126     brouard  1206: #include <unistd.h>
1.159     brouard  1207: #endif
1.126     brouard  1208: 
                   1209: #include <limits.h>
                   1210: #include <sys/types.h>
1.171     brouard  1211: 
                   1212: #if defined(__GNUC__)
                   1213: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1214: #endif
                   1215: 
1.126     brouard  1216: #include <sys/stat.h>
                   1217: #include <errno.h>
1.159     brouard  1218: /* extern int errno; */
1.126     brouard  1219: 
1.157     brouard  1220: /* #ifdef LINUX */
                   1221: /* #include <time.h> */
                   1222: /* #include "timeval.h" */
                   1223: /* #else */
                   1224: /* #include <sys/time.h> */
                   1225: /* #endif */
                   1226: 
1.126     brouard  1227: #include <time.h>
                   1228: 
1.136     brouard  1229: #ifdef GSL
                   1230: #include <gsl/gsl_errno.h>
                   1231: #include <gsl/gsl_multimin.h>
                   1232: #endif
                   1233: 
1.167     brouard  1234: 
1.162     brouard  1235: #ifdef NLOPT
                   1236: #include <nlopt.h>
                   1237: typedef struct {
                   1238:   double (* function)(double [] );
                   1239: } myfunc_data ;
                   1240: #endif
                   1241: 
1.126     brouard  1242: /* #include <libintl.h> */
                   1243: /* #define _(String) gettext (String) */
                   1244: 
1.251     brouard  1245: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1246: 
                   1247: #define GNUPLOTPROGRAM "gnuplot"
                   1248: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1249: #define FILENAMELENGTH 256
1.126     brouard  1250: 
                   1251: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1252: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1253: 
1.144     brouard  1254: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1255: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1256: 
                   1257: #define NINTERVMAX 8
1.144     brouard  1258: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1259: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1260: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1261: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1262: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1263: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1264: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1265: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1266: /* #define AGESUP 130 */
1.288     brouard  1267: /* #define AGESUP 150 */
                   1268: #define AGESUP 200
1.268     brouard  1269: #define AGEINF 0
1.218     brouard  1270: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1271: #define AGEBASE 40
1.194     brouard  1272: #define AGEOVERFLOW 1.e20
1.164     brouard  1273: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1274: #ifdef _WIN32
                   1275: #define DIRSEPARATOR '\\'
                   1276: #define CHARSEPARATOR "\\"
                   1277: #define ODIRSEPARATOR '/'
                   1278: #else
1.126     brouard  1279: #define DIRSEPARATOR '/'
                   1280: #define CHARSEPARATOR "/"
                   1281: #define ODIRSEPARATOR '\\'
                   1282: #endif
                   1283: 
1.335   ! brouard  1284: /* $Id: imach.c,v 1.334 2022/08/25 09:08:41 brouard Exp $ */
1.126     brouard  1285: /* $State: Exp $ */
1.196     brouard  1286: #include "version.h"
                   1287: char version[]=__IMACH_VERSION__;
1.332     brouard  1288: 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.335   ! brouard  1289: char fullversion[]="$Revision: 1.334 $ $Date: 2022/08/25 09:08:41 $"; 
1.126     brouard  1290: char strstart[80];
                   1291: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1292: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1293: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1294: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1295: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335   ! brouard  1296: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
1.330     brouard  1297: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.335   ! brouard  1298: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
        !          1299: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1300: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1301: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335   ! brouard  1302: int cptcoveff=0; /* Total number of single dummy covariates (fixed or time varying) to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1303: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1304: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1305: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1306: int nsd=0; /**< Total number of single dummy variables (output) */
                   1307: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1308: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1309: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1310: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1311: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1312: int cptcov=0; /* Working variable */
1.334     brouard  1313: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1314: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1315: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1316: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1317: int nlstate=2; /* Number of live states */
                   1318: int ndeath=1; /* Number of dead states */
1.130     brouard  1319: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1320: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1321: int popbased=0;
                   1322: 
                   1323: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1324: int maxwav=0; /* Maxim number of waves */
                   1325: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1326: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1327: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1328:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1329: int mle=1, weightopt=0;
1.126     brouard  1330: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1331: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1332: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1333:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1334: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1335: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1336: 
1.130     brouard  1337: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1338: double **matprod2(); /* test */
1.126     brouard  1339: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1340: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1341: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1342: 
1.136     brouard  1343: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1344: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1345: FILE *ficlog, *ficrespow;
1.130     brouard  1346: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1347: double fretone; /* Only one call to likelihood */
1.130     brouard  1348: long ipmx=0; /* Number of contributions */
1.126     brouard  1349: double sw; /* Sum of weights */
                   1350: char filerespow[FILENAMELENGTH];
                   1351: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1352: FILE *ficresilk;
                   1353: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1354: FILE *ficresprobmorprev;
                   1355: FILE *fichtm, *fichtmcov; /* Html File */
                   1356: FILE *ficreseij;
                   1357: char filerese[FILENAMELENGTH];
                   1358: FILE *ficresstdeij;
                   1359: char fileresstde[FILENAMELENGTH];
                   1360: FILE *ficrescveij;
                   1361: char filerescve[FILENAMELENGTH];
                   1362: FILE  *ficresvij;
                   1363: char fileresv[FILENAMELENGTH];
1.269     brouard  1364: 
1.126     brouard  1365: char title[MAXLINE];
1.234     brouard  1366: char model[MAXLINE]; /**< The model line */
1.217     brouard  1367: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1368: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1369: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1370: char command[FILENAMELENGTH];
                   1371: int  outcmd=0;
                   1372: 
1.217     brouard  1373: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1374: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1375: char filelog[FILENAMELENGTH]; /* Log file */
                   1376: char filerest[FILENAMELENGTH];
                   1377: char fileregp[FILENAMELENGTH];
                   1378: char popfile[FILENAMELENGTH];
                   1379: 
                   1380: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1381: 
1.157     brouard  1382: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1383: /* struct timezone tzp; */
                   1384: /* extern int gettimeofday(); */
                   1385: struct tm tml, *gmtime(), *localtime();
                   1386: 
                   1387: extern time_t time();
                   1388: 
                   1389: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1390: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1391: struct tm tm;
                   1392: 
1.126     brouard  1393: char strcurr[80], strfor[80];
                   1394: 
                   1395: char *endptr;
                   1396: long lval;
                   1397: double dval;
                   1398: 
                   1399: #define NR_END 1
                   1400: #define FREE_ARG char*
                   1401: #define FTOL 1.0e-10
                   1402: 
                   1403: #define NRANSI 
1.240     brouard  1404: #define ITMAX 200
                   1405: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1406: 
                   1407: #define TOL 2.0e-4 
                   1408: 
                   1409: #define CGOLD 0.3819660 
                   1410: #define ZEPS 1.0e-10 
                   1411: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1412: 
                   1413: #define GOLD 1.618034 
                   1414: #define GLIMIT 100.0 
                   1415: #define TINY 1.0e-20 
                   1416: 
                   1417: static double maxarg1,maxarg2;
                   1418: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1419: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1420:   
                   1421: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1422: #define rint(a) floor(a+0.5)
1.166     brouard  1423: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1424: #define mytinydouble 1.0e-16
1.166     brouard  1425: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1426: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1427: /* static double dsqrarg; */
                   1428: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1429: static double sqrarg;
                   1430: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1431: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1432: int agegomp= AGEGOMP;
                   1433: 
                   1434: int imx; 
                   1435: int stepm=1;
                   1436: /* Stepm, step in month: minimum step interpolation*/
                   1437: 
                   1438: int estepm;
                   1439: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1440: 
                   1441: int m,nb;
                   1442: long *num;
1.197     brouard  1443: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1444: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1445:                   covariate for which somebody answered excluding 
                   1446:                   undefined. Usually 2: 0 and 1. */
                   1447: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1448:                             covariate for which somebody answered including 
                   1449:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1450: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1451: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1452: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1453: 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  1454: double *ageexmed,*agecens;
                   1455: double dateintmean=0;
1.296     brouard  1456:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1457:   double anprojf, mprojf, jprojf;
1.126     brouard  1458: 
1.296     brouard  1459:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1460:   double anbackf, mbackf, jbackf;
                   1461:   double jintmean,mintmean,aintmean;  
1.126     brouard  1462: double *weight;
                   1463: int **s; /* Status */
1.141     brouard  1464: double *agedc;
1.145     brouard  1465: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1466:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1467:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1468: double **coqvar; /* Fixed quantitative covariate nqv */
                   1469: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1470: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1471: double  idx; 
                   1472: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1473: /* Some documentation */
                   1474:       /*   Design original data
                   1475:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1476:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1477:        *                                                             ntv=3     nqtv=1
1.330     brouard  1478:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1479:        * For time varying covariate, quanti or dummies
                   1480:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1481:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1482:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1483:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1484:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1485:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1486:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1487:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1488:        */
                   1489: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1490: /* 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
                   1491:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1492:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1493: */
1.319     brouard  1494: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1495: /*    k        1  2   3   4     5    6    7     8    9 */
                   1496: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1497:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1498:                                                          /* product */
                   1499: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1500:                                                          /*(single or product without age), 2 dummy*/
                   1501:                                                          /* with age product, 3 quant with age product*/
                   1502: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1503: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1504: /*TnsdVar[Tvar]   1   2                              3 */ 
1.319     brouard  1505: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
                   1506: /*TvarsDind[k]    2   3                              9 */ /* position K of single dummy cova */
                   1507: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1508: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1509: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1510: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1511: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1512: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1513: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1514: /* 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  1515: /* 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  1516: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1517: /* Type                    */
                   1518: /* V         1  2  3  4  5 */
                   1519: /*           F  F  V  V  V */
                   1520: /*           D  Q  D  D  Q */
                   1521: /*                         */
                   1522: int *TvarsD;
1.330     brouard  1523: int *TnsdVar;
1.234     brouard  1524: int *TvarsDind;
                   1525: int *TvarsQ;
                   1526: int *TvarsQind;
                   1527: 
1.318     brouard  1528: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1529: int nresult=0;
1.258     brouard  1530: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1531: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1532: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1533: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1534: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1535: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1536: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1537: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1538: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1539: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1540: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1541: 
                   1542: /* 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
                   1543:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1544:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1545: */
1.234     brouard  1546: /* 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  1547: 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 */
                   1548: 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 */
                   1549: 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 */
                   1550: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1551: 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 */
                   1552: 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  1553: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1554: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1555: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1556: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1557: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1558: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1559: 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 */
                   1560: 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 */
                   1561: 
1.230     brouard  1562: int *Tvarsel; /**< Selected covariates for output */
                   1563: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1564: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1565: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1566: 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  1567: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1568: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1569: int *Tage;
1.227     brouard  1570: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1571: 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  1572: 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*/ 
                   1573: 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  1574: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1575: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1576: int **Tvard;
1.330     brouard  1577: int **Tvardk;
1.227     brouard  1578: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1579: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1580: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1581:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1582:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1583: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1584: double *lsurv, *lpop, *tpop;
                   1585: 
1.231     brouard  1586: #define FD 1; /* Fixed dummy covariate */
                   1587: #define FQ 2; /* Fixed quantitative covariate */
                   1588: #define FP 3; /* Fixed product covariate */
                   1589: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1590: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1591: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1592: #define VD 10; /* Varying dummy covariate */
                   1593: #define VQ 11; /* Varying quantitative covariate */
                   1594: #define VP 12; /* Varying product covariate */
                   1595: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1596: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1597: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1598: #define APFD 16; /* Age product * fixed dummy covariate */
                   1599: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1600: #define APVD 18; /* Age product * varying dummy covariate */
                   1601: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1602: 
                   1603: #define FTYPE 1; /* Fixed covariate */
                   1604: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1605: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1606: 
                   1607: struct kmodel{
                   1608:        int maintype; /* main type */
                   1609:        int subtype; /* subtype */
                   1610: };
                   1611: struct kmodel modell[NCOVMAX];
                   1612: 
1.143     brouard  1613: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1614: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1615: 
                   1616: /**************** split *************************/
                   1617: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1618: {
                   1619:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1620:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1621:   */ 
                   1622:   char *ss;                            /* pointer */
1.186     brouard  1623:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1624: 
                   1625:   l1 = strlen(path );                  /* length of path */
                   1626:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1627:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1628:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1629:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1630:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1631:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1632:     /* get current working directory */
                   1633:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1634: #ifdef WIN32
                   1635:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1636: #else
                   1637:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1638: #endif
1.126     brouard  1639:       return( GLOCK_ERROR_GETCWD );
                   1640:     }
                   1641:     /* got dirc from getcwd*/
                   1642:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1643:   } else {                             /* strip directory from path */
1.126     brouard  1644:     ss++;                              /* after this, the filename */
                   1645:     l2 = strlen( ss );                 /* length of filename */
                   1646:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1647:     strcpy( name, ss );                /* save file name */
                   1648:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1649:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1650:     printf(" DIRC2 = %s \n",dirc);
                   1651:   }
                   1652:   /* We add a separator at the end of dirc if not exists */
                   1653:   l1 = strlen( dirc );                 /* length of directory */
                   1654:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1655:     dirc[l1] =  DIRSEPARATOR;
                   1656:     dirc[l1+1] = 0; 
                   1657:     printf(" DIRC3 = %s \n",dirc);
                   1658:   }
                   1659:   ss = strrchr( name, '.' );           /* find last / */
                   1660:   if (ss >0){
                   1661:     ss++;
                   1662:     strcpy(ext,ss);                    /* save extension */
                   1663:     l1= strlen( name);
                   1664:     l2= strlen(ss)+1;
                   1665:     strncpy( finame, name, l1-l2);
                   1666:     finame[l1-l2]= 0;
                   1667:   }
                   1668: 
                   1669:   return( 0 );                         /* we're done */
                   1670: }
                   1671: 
                   1672: 
                   1673: /******************************************/
                   1674: 
                   1675: void replace_back_to_slash(char *s, char*t)
                   1676: {
                   1677:   int i;
                   1678:   int lg=0;
                   1679:   i=0;
                   1680:   lg=strlen(t);
                   1681:   for(i=0; i<= lg; i++) {
                   1682:     (s[i] = t[i]);
                   1683:     if (t[i]== '\\') s[i]='/';
                   1684:   }
                   1685: }
                   1686: 
1.132     brouard  1687: char *trimbb(char *out, char *in)
1.137     brouard  1688: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1689:   char *s;
                   1690:   s=out;
                   1691:   while (*in != '\0'){
1.137     brouard  1692:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1693:       in++;
                   1694:     }
                   1695:     *out++ = *in++;
                   1696:   }
                   1697:   *out='\0';
                   1698:   return s;
                   1699: }
                   1700: 
1.187     brouard  1701: /* char *substrchaine(char *out, char *in, char *chain) */
                   1702: /* { */
                   1703: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1704: /*   char *s, *t; */
                   1705: /*   t=in;s=out; */
                   1706: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1707: /*     *out++ = *in++; */
                   1708: /*   } */
                   1709: 
                   1710: /*   /\* *in matches *chain *\/ */
                   1711: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1712: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1713: /*   } */
                   1714: /*   in--; chain--; */
                   1715: /*   while ( (*in != '\0')){ */
                   1716: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1717: /*     *out++ = *in++; */
                   1718: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1719: /*   } */
                   1720: /*   *out='\0'; */
                   1721: /*   out=s; */
                   1722: /*   return out; */
                   1723: /* } */
                   1724: char *substrchaine(char *out, char *in, char *chain)
                   1725: {
                   1726:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1727:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1728: 
                   1729:   char *strloc;
                   1730: 
                   1731:   strcpy (out, in); 
                   1732:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1733:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1734:   if(strloc != NULL){ 
                   1735:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1736:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1737:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1738:   }
                   1739:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1740:   return out;
                   1741: }
                   1742: 
                   1743: 
1.145     brouard  1744: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1745: {
1.187     brouard  1746:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1747:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1748:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1749:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1750:   */
1.160     brouard  1751:   char *s, *t;
1.145     brouard  1752:   t=in;s=in;
                   1753:   while ((*in != occ) && (*in != '\0')){
                   1754:     *alocc++ = *in++;
                   1755:   }
                   1756:   if( *in == occ){
                   1757:     *(alocc)='\0';
                   1758:     s=++in;
                   1759:   }
                   1760:  
                   1761:   if (s == t) {/* occ not found */
                   1762:     *(alocc-(in-s))='\0';
                   1763:     in=s;
                   1764:   }
                   1765:   while ( *in != '\0'){
                   1766:     *blocc++ = *in++;
                   1767:   }
                   1768: 
                   1769:   *blocc='\0';
                   1770:   return t;
                   1771: }
1.137     brouard  1772: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1773: {
1.187     brouard  1774:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1775:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1776:      gives blocc="abcdef2ghi" and alocc="j".
                   1777:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1778:   */
                   1779:   char *s, *t;
                   1780:   t=in;s=in;
                   1781:   while (*in != '\0'){
                   1782:     while( *in == occ){
                   1783:       *blocc++ = *in++;
                   1784:       s=in;
                   1785:     }
                   1786:     *blocc++ = *in++;
                   1787:   }
                   1788:   if (s == t) /* occ not found */
                   1789:     *(blocc-(in-s))='\0';
                   1790:   else
                   1791:     *(blocc-(in-s)-1)='\0';
                   1792:   in=s;
                   1793:   while ( *in != '\0'){
                   1794:     *alocc++ = *in++;
                   1795:   }
                   1796: 
                   1797:   *alocc='\0';
                   1798:   return s;
                   1799: }
                   1800: 
1.126     brouard  1801: int nbocc(char *s, char occ)
                   1802: {
                   1803:   int i,j=0;
                   1804:   int lg=20;
                   1805:   i=0;
                   1806:   lg=strlen(s);
                   1807:   for(i=0; i<= lg; i++) {
1.234     brouard  1808:     if  (s[i] == occ ) j++;
1.126     brouard  1809:   }
                   1810:   return j;
                   1811: }
                   1812: 
1.137     brouard  1813: /* void cutv(char *u,char *v, char*t, char occ) */
                   1814: /* { */
                   1815: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1816: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1817: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1818: /*   int i,lg,j,p=0; */
                   1819: /*   i=0; */
                   1820: /*   lg=strlen(t); */
                   1821: /*   for(j=0; j<=lg-1; j++) { */
                   1822: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1823: /*   } */
1.126     brouard  1824: 
1.137     brouard  1825: /*   for(j=0; j<p; j++) { */
                   1826: /*     (u[j] = t[j]); */
                   1827: /*   } */
                   1828: /*      u[p]='\0'; */
1.126     brouard  1829: 
1.137     brouard  1830: /*    for(j=0; j<= lg; j++) { */
                   1831: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1832: /*   } */
                   1833: /* } */
1.126     brouard  1834: 
1.160     brouard  1835: #ifdef _WIN32
                   1836: char * strsep(char **pp, const char *delim)
                   1837: {
                   1838:   char *p, *q;
                   1839:          
                   1840:   if ((p = *pp) == NULL)
                   1841:     return 0;
                   1842:   if ((q = strpbrk (p, delim)) != NULL)
                   1843:   {
                   1844:     *pp = q + 1;
                   1845:     *q = '\0';
                   1846:   }
                   1847:   else
                   1848:     *pp = 0;
                   1849:   return p;
                   1850: }
                   1851: #endif
                   1852: 
1.126     brouard  1853: /********************** nrerror ********************/
                   1854: 
                   1855: void nrerror(char error_text[])
                   1856: {
                   1857:   fprintf(stderr,"ERREUR ...\n");
                   1858:   fprintf(stderr,"%s\n",error_text);
                   1859:   exit(EXIT_FAILURE);
                   1860: }
                   1861: /*********************** vector *******************/
                   1862: double *vector(int nl, int nh)
                   1863: {
                   1864:   double *v;
                   1865:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1866:   if (!v) nrerror("allocation failure in vector");
                   1867:   return v-nl+NR_END;
                   1868: }
                   1869: 
                   1870: /************************ free vector ******************/
                   1871: void free_vector(double*v, int nl, int nh)
                   1872: {
                   1873:   free((FREE_ARG)(v+nl-NR_END));
                   1874: }
                   1875: 
                   1876: /************************ivector *******************************/
                   1877: int *ivector(long nl,long nh)
                   1878: {
                   1879:   int *v;
                   1880:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1881:   if (!v) nrerror("allocation failure in ivector");
                   1882:   return v-nl+NR_END;
                   1883: }
                   1884: 
                   1885: /******************free ivector **************************/
                   1886: void free_ivector(int *v, long nl, long nh)
                   1887: {
                   1888:   free((FREE_ARG)(v+nl-NR_END));
                   1889: }
                   1890: 
                   1891: /************************lvector *******************************/
                   1892: long *lvector(long nl,long nh)
                   1893: {
                   1894:   long *v;
                   1895:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1896:   if (!v) nrerror("allocation failure in ivector");
                   1897:   return v-nl+NR_END;
                   1898: }
                   1899: 
                   1900: /******************free lvector **************************/
                   1901: void free_lvector(long *v, long nl, long nh)
                   1902: {
                   1903:   free((FREE_ARG)(v+nl-NR_END));
                   1904: }
                   1905: 
                   1906: /******************* imatrix *******************************/
                   1907: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1908:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1909: { 
                   1910:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1911:   int **m; 
                   1912:   
                   1913:   /* allocate pointers to rows */ 
                   1914:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1915:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1916:   m += NR_END; 
                   1917:   m -= nrl; 
                   1918:   
                   1919:   
                   1920:   /* allocate rows and set pointers to them */ 
                   1921:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1922:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1923:   m[nrl] += NR_END; 
                   1924:   m[nrl] -= ncl; 
                   1925:   
                   1926:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1927:   
                   1928:   /* return pointer to array of pointers to rows */ 
                   1929:   return m; 
                   1930: } 
                   1931: 
                   1932: /****************** free_imatrix *************************/
                   1933: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1934:       int **m;
                   1935:       long nch,ncl,nrh,nrl; 
                   1936:      /* free an int matrix allocated by imatrix() */ 
                   1937: { 
                   1938:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1939:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1940: } 
                   1941: 
                   1942: /******************* matrix *******************************/
                   1943: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1944: {
                   1945:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1946:   double **m;
                   1947: 
                   1948:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1949:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1950:   m += NR_END;
                   1951:   m -= nrl;
                   1952: 
                   1953:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1954:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1955:   m[nrl] += NR_END;
                   1956:   m[nrl] -= ncl;
                   1957: 
                   1958:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1959:   return m;
1.145     brouard  1960:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1961: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1962: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1963:    */
                   1964: }
                   1965: 
                   1966: /*************************free matrix ************************/
                   1967: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1968: {
                   1969:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1970:   free((FREE_ARG)(m+nrl-NR_END));
                   1971: }
                   1972: 
                   1973: /******************* ma3x *******************************/
                   1974: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1975: {
                   1976:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1977:   double ***m;
                   1978: 
                   1979:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1980:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1981:   m += NR_END;
                   1982:   m -= nrl;
                   1983: 
                   1984:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1985:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1986:   m[nrl] += NR_END;
                   1987:   m[nrl] -= ncl;
                   1988: 
                   1989:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1990: 
                   1991:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1992:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1993:   m[nrl][ncl] += NR_END;
                   1994:   m[nrl][ncl] -= nll;
                   1995:   for (j=ncl+1; j<=nch; j++) 
                   1996:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1997:   
                   1998:   for (i=nrl+1; i<=nrh; i++) {
                   1999:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2000:     for (j=ncl+1; j<=nch; j++) 
                   2001:       m[i][j]=m[i][j-1]+nlay;
                   2002:   }
                   2003:   return m; 
                   2004:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2005:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2006:   */
                   2007: }
                   2008: 
                   2009: /*************************free ma3x ************************/
                   2010: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2011: {
                   2012:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2013:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2014:   free((FREE_ARG)(m+nrl-NR_END));
                   2015: }
                   2016: 
                   2017: /*************** function subdirf ***********/
                   2018: char *subdirf(char fileres[])
                   2019: {
                   2020:   /* Caution optionfilefiname is hidden */
                   2021:   strcpy(tmpout,optionfilefiname);
                   2022:   strcat(tmpout,"/"); /* Add to the right */
                   2023:   strcat(tmpout,fileres);
                   2024:   return tmpout;
                   2025: }
                   2026: 
                   2027: /*************** function subdirf2 ***********/
                   2028: char *subdirf2(char fileres[], char *preop)
                   2029: {
1.314     brouard  2030:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2031:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2032:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2033:   /* Caution optionfilefiname is hidden */
                   2034:   strcpy(tmpout,optionfilefiname);
                   2035:   strcat(tmpout,"/");
                   2036:   strcat(tmpout,preop);
                   2037:   strcat(tmpout,fileres);
                   2038:   return tmpout;
                   2039: }
                   2040: 
                   2041: /*************** function subdirf3 ***********/
                   2042: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2043: {
                   2044:   
                   2045:   /* Caution optionfilefiname is hidden */
                   2046:   strcpy(tmpout,optionfilefiname);
                   2047:   strcat(tmpout,"/");
                   2048:   strcat(tmpout,preop);
                   2049:   strcat(tmpout,preop2);
                   2050:   strcat(tmpout,fileres);
                   2051:   return tmpout;
                   2052: }
1.213     brouard  2053:  
                   2054: /*************** function subdirfext ***********/
                   2055: char *subdirfext(char fileres[], char *preop, char *postop)
                   2056: {
                   2057:   
                   2058:   strcpy(tmpout,preop);
                   2059:   strcat(tmpout,fileres);
                   2060:   strcat(tmpout,postop);
                   2061:   return tmpout;
                   2062: }
1.126     brouard  2063: 
1.213     brouard  2064: /*************** function subdirfext3 ***********/
                   2065: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2066: {
                   2067:   
                   2068:   /* Caution optionfilefiname is hidden */
                   2069:   strcpy(tmpout,optionfilefiname);
                   2070:   strcat(tmpout,"/");
                   2071:   strcat(tmpout,preop);
                   2072:   strcat(tmpout,fileres);
                   2073:   strcat(tmpout,postop);
                   2074:   return tmpout;
                   2075: }
                   2076:  
1.162     brouard  2077: char *asc_diff_time(long time_sec, char ascdiff[])
                   2078: {
                   2079:   long sec_left, days, hours, minutes;
                   2080:   days = (time_sec) / (60*60*24);
                   2081:   sec_left = (time_sec) % (60*60*24);
                   2082:   hours = (sec_left) / (60*60) ;
                   2083:   sec_left = (sec_left) %(60*60);
                   2084:   minutes = (sec_left) /60;
                   2085:   sec_left = (sec_left) % (60);
                   2086:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2087:   return ascdiff;
                   2088: }
                   2089: 
1.126     brouard  2090: /***************** f1dim *************************/
                   2091: extern int ncom; 
                   2092: extern double *pcom,*xicom;
                   2093: extern double (*nrfunc)(double []); 
                   2094:  
                   2095: double f1dim(double x) 
                   2096: { 
                   2097:   int j; 
                   2098:   double f;
                   2099:   double *xt; 
                   2100:  
                   2101:   xt=vector(1,ncom); 
                   2102:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2103:   f=(*nrfunc)(xt); 
                   2104:   free_vector(xt,1,ncom); 
                   2105:   return f; 
                   2106: } 
                   2107: 
                   2108: /*****************brent *************************/
                   2109: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2110: {
                   2111:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2112:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2113:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2114:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2115:    * returned function value. 
                   2116:   */
1.126     brouard  2117:   int iter; 
                   2118:   double a,b,d,etemp;
1.159     brouard  2119:   double fu=0,fv,fw,fx;
1.164     brouard  2120:   double ftemp=0.;
1.126     brouard  2121:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2122:   double e=0.0; 
                   2123:  
                   2124:   a=(ax < cx ? ax : cx); 
                   2125:   b=(ax > cx ? ax : cx); 
                   2126:   x=w=v=bx; 
                   2127:   fw=fv=fx=(*f)(x); 
                   2128:   for (iter=1;iter<=ITMAX;iter++) { 
                   2129:     xm=0.5*(a+b); 
                   2130:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2131:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2132:     printf(".");fflush(stdout);
                   2133:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2134: #ifdef DEBUGBRENT
1.126     brouard  2135:     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);
                   2136:     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);
                   2137:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2138: #endif
                   2139:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2140:       *xmin=x; 
                   2141:       return fx; 
                   2142:     } 
                   2143:     ftemp=fu;
                   2144:     if (fabs(e) > tol1) { 
                   2145:       r=(x-w)*(fx-fv); 
                   2146:       q=(x-v)*(fx-fw); 
                   2147:       p=(x-v)*q-(x-w)*r; 
                   2148:       q=2.0*(q-r); 
                   2149:       if (q > 0.0) p = -p; 
                   2150:       q=fabs(q); 
                   2151:       etemp=e; 
                   2152:       e=d; 
                   2153:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2154:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2155:       else { 
1.224     brouard  2156:                                d=p/q; 
                   2157:                                u=x+d; 
                   2158:                                if (u-a < tol2 || b-u < tol2) 
                   2159:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2160:       } 
                   2161:     } else { 
                   2162:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2163:     } 
                   2164:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2165:     fu=(*f)(u); 
                   2166:     if (fu <= fx) { 
                   2167:       if (u >= x) a=x; else b=x; 
                   2168:       SHFT(v,w,x,u) 
1.183     brouard  2169:       SHFT(fv,fw,fx,fu) 
                   2170:     } else { 
                   2171:       if (u < x) a=u; else b=u; 
                   2172:       if (fu <= fw || w == x) { 
1.224     brouard  2173:                                v=w; 
                   2174:                                w=u; 
                   2175:                                fv=fw; 
                   2176:                                fw=fu; 
1.183     brouard  2177:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2178:                                v=u; 
                   2179:                                fv=fu; 
1.183     brouard  2180:       } 
                   2181:     } 
1.126     brouard  2182:   } 
                   2183:   nrerror("Too many iterations in brent"); 
                   2184:   *xmin=x; 
                   2185:   return fx; 
                   2186: } 
                   2187: 
                   2188: /****************** mnbrak ***********************/
                   2189: 
                   2190: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2191:            double (*func)(double)) 
1.183     brouard  2192: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2193: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2194: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2195: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2196:    */
1.126     brouard  2197:   double ulim,u,r,q, dum;
                   2198:   double fu; 
1.187     brouard  2199: 
                   2200:   double scale=10.;
                   2201:   int iterscale=0;
                   2202: 
                   2203:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2204:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2205: 
                   2206: 
                   2207:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2208:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2209:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2210:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2211:   /* } */
                   2212: 
1.126     brouard  2213:   if (*fb > *fa) { 
                   2214:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2215:     SHFT(dum,*fb,*fa,dum) 
                   2216:   } 
1.126     brouard  2217:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2218:   *fc=(*func)(*cx); 
1.183     brouard  2219: #ifdef DEBUG
1.224     brouard  2220:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2221:   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  2222: #endif
1.224     brouard  2223:   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  2224:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2225:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2226:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2227:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2228:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2229:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2230:       fu=(*func)(u); 
1.163     brouard  2231: #ifdef DEBUG
                   2232:       /* f(x)=A(x-u)**2+f(u) */
                   2233:       double A, fparabu; 
                   2234:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2235:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2236:       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);
                   2237:       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  2238:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2239:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2240:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2241:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2242: #endif 
1.184     brouard  2243: #ifdef MNBRAKORIGINAL
1.183     brouard  2244: #else
1.191     brouard  2245: /*       if (fu > *fc) { */
                   2246: /* #ifdef DEBUG */
                   2247: /*       printf("mnbrak4  fu > fc \n"); */
                   2248: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2249: /* #endif */
                   2250: /*     /\* 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 *\\/  *\/ */
                   2251: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2252: /*     dum=u; /\* Shifting c and u *\/ */
                   2253: /*     u = *cx; */
                   2254: /*     *cx = dum; */
                   2255: /*     dum = fu; */
                   2256: /*     fu = *fc; */
                   2257: /*     *fc =dum; */
                   2258: /*       } else { /\* end *\/ */
                   2259: /* #ifdef DEBUG */
                   2260: /*       printf("mnbrak3  fu < fc \n"); */
                   2261: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2262: /* #endif */
                   2263: /*     dum=u; /\* Shifting c and u *\/ */
                   2264: /*     u = *cx; */
                   2265: /*     *cx = dum; */
                   2266: /*     dum = fu; */
                   2267: /*     fu = *fc; */
                   2268: /*     *fc =dum; */
                   2269: /*       } */
1.224     brouard  2270: #ifdef DEBUGMNBRAK
                   2271:                 double A, fparabu; 
                   2272:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2273:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2274:      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);
                   2275:      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  2276: #endif
1.191     brouard  2277:       dum=u; /* Shifting c and u */
                   2278:       u = *cx;
                   2279:       *cx = dum;
                   2280:       dum = fu;
                   2281:       fu = *fc;
                   2282:       *fc =dum;
1.183     brouard  2283: #endif
1.162     brouard  2284:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2285: #ifdef DEBUG
1.224     brouard  2286:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2287:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2288: #endif
1.126     brouard  2289:       fu=(*func)(u); 
                   2290:       if (fu < *fc) { 
1.183     brouard  2291: #ifdef DEBUG
1.224     brouard  2292:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2293:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2294: #endif
                   2295:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2296:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2297: #ifdef DEBUG
                   2298:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2299: #endif
                   2300:       } 
1.162     brouard  2301:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2302: #ifdef DEBUG
1.224     brouard  2303:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2304:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2305: #endif
1.126     brouard  2306:       u=ulim; 
                   2307:       fu=(*func)(u); 
1.183     brouard  2308:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2309: #ifdef DEBUG
1.224     brouard  2310:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2311:       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  2312: #endif
1.126     brouard  2313:       u=(*cx)+GOLD*(*cx-*bx); 
                   2314:       fu=(*func)(u); 
1.224     brouard  2315: #ifdef DEBUG
                   2316:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2317:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2318: #endif
1.183     brouard  2319:     } /* end tests */
1.126     brouard  2320:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2321:     SHFT(*fa,*fb,*fc,fu) 
                   2322: #ifdef DEBUG
1.224     brouard  2323:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2324:       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  2325: #endif
                   2326:   } /* 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  2327: } 
                   2328: 
                   2329: /*************** linmin ************************/
1.162     brouard  2330: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2331: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2332: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2333: the value of func at the returned location p . This is actually all accomplished by calling the
                   2334: routines mnbrak and brent .*/
1.126     brouard  2335: int ncom; 
                   2336: double *pcom,*xicom;
                   2337: double (*nrfunc)(double []); 
                   2338:  
1.224     brouard  2339: #ifdef LINMINORIGINAL
1.126     brouard  2340: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2341: #else
                   2342: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2343: #endif
1.126     brouard  2344: { 
                   2345:   double brent(double ax, double bx, double cx, 
                   2346:               double (*f)(double), double tol, double *xmin); 
                   2347:   double f1dim(double x); 
                   2348:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2349:              double *fc, double (*func)(double)); 
                   2350:   int j; 
                   2351:   double xx,xmin,bx,ax; 
                   2352:   double fx,fb,fa;
1.187     brouard  2353: 
1.203     brouard  2354: #ifdef LINMINORIGINAL
                   2355: #else
                   2356:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2357: #endif
                   2358:   
1.126     brouard  2359:   ncom=n; 
                   2360:   pcom=vector(1,n); 
                   2361:   xicom=vector(1,n); 
                   2362:   nrfunc=func; 
                   2363:   for (j=1;j<=n;j++) { 
                   2364:     pcom[j]=p[j]; 
1.202     brouard  2365:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2366:   } 
1.187     brouard  2367: 
1.203     brouard  2368: #ifdef LINMINORIGINAL
                   2369:   xx=1.;
                   2370: #else
                   2371:   axs=0.0;
                   2372:   xxs=1.;
                   2373:   do{
                   2374:     xx= xxs;
                   2375: #endif
1.187     brouard  2376:     ax=0.;
                   2377:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2378:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2379:     /* 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))   */
                   2380:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2381:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2382:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2383:     /* 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  2384: #ifdef LINMINORIGINAL
                   2385: #else
                   2386:     if (fx != fx){
1.224     brouard  2387:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2388:                        printf("|");
                   2389:                        fprintf(ficlog,"|");
1.203     brouard  2390: #ifdef DEBUGLINMIN
1.224     brouard  2391:                        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  2392: #endif
                   2393:     }
1.224     brouard  2394:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2395: #endif
                   2396:   
1.191     brouard  2397: #ifdef DEBUGLINMIN
                   2398:   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  2399:   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  2400: #endif
1.224     brouard  2401: #ifdef LINMINORIGINAL
                   2402: #else
1.317     brouard  2403:   if(fb == fx){ /* Flat function in the direction */
                   2404:     xmin=xx;
1.224     brouard  2405:     *flat=1;
1.317     brouard  2406:   }else{
1.224     brouard  2407:     *flat=0;
                   2408: #endif
                   2409:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2410:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2411:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2412:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2413:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2414:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2415: #ifdef DEBUG
1.224     brouard  2416:   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);
                   2417:   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);
                   2418: #endif
                   2419: #ifdef LINMINORIGINAL
                   2420: #else
                   2421:                        }
1.126     brouard  2422: #endif
1.191     brouard  2423: #ifdef DEBUGLINMIN
                   2424:   printf("linmin end ");
1.202     brouard  2425:   fprintf(ficlog,"linmin end ");
1.191     brouard  2426: #endif
1.126     brouard  2427:   for (j=1;j<=n;j++) { 
1.203     brouard  2428: #ifdef LINMINORIGINAL
                   2429:     xi[j] *= xmin; 
                   2430: #else
                   2431: #ifdef DEBUGLINMIN
                   2432:     if(xxs <1.0)
                   2433:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2434: #endif
                   2435:     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) */
                   2436: #ifdef DEBUGLINMIN
                   2437:     if(xxs <1.0)
                   2438:       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 );
                   2439: #endif
                   2440: #endif
1.187     brouard  2441:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2442:   } 
1.191     brouard  2443: #ifdef DEBUGLINMIN
1.203     brouard  2444:   printf("\n");
1.191     brouard  2445:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2446:   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  2447:   for (j=1;j<=n;j++) { 
1.202     brouard  2448:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2449:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2450:     if(j % ncovmodel == 0){
1.191     brouard  2451:       printf("\n");
1.202     brouard  2452:       fprintf(ficlog,"\n");
                   2453:     }
1.191     brouard  2454:   }
1.203     brouard  2455: #else
1.191     brouard  2456: #endif
1.126     brouard  2457:   free_vector(xicom,1,n); 
                   2458:   free_vector(pcom,1,n); 
                   2459: } 
                   2460: 
                   2461: 
                   2462: /*************** powell ************************/
1.162     brouard  2463: /*
1.317     brouard  2464: Minimization of a function func of n variables. Input consists in an initial starting point
                   2465: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2466: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2467: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2468: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2469: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2470:  */
1.224     brouard  2471: #ifdef LINMINORIGINAL
                   2472: #else
                   2473:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2474:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2475: #endif
1.126     brouard  2476: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2477:            double (*func)(double [])) 
                   2478: { 
1.224     brouard  2479: #ifdef LINMINORIGINAL
                   2480:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2481:              double (*func)(double [])); 
1.224     brouard  2482: #else 
1.241     brouard  2483:  void linmin(double p[], double xi[], int n, double *fret,
                   2484:             double (*func)(double []),int *flat); 
1.224     brouard  2485: #endif
1.239     brouard  2486:  int i,ibig,j,jk,k; 
1.126     brouard  2487:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2488:   double directest;
1.126     brouard  2489:   double fp,fptt;
                   2490:   double *xits;
                   2491:   int niterf, itmp;
                   2492: 
                   2493:   pt=vector(1,n); 
                   2494:   ptt=vector(1,n); 
                   2495:   xit=vector(1,n); 
                   2496:   xits=vector(1,n); 
                   2497:   *fret=(*func)(p); 
                   2498:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2499:   rcurr_time = time(NULL);  
1.126     brouard  2500:   for (*iter=1;;++(*iter)) { 
                   2501:     ibig=0; 
                   2502:     del=0.0; 
1.157     brouard  2503:     rlast_time=rcurr_time;
                   2504:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2505:     rcurr_time = time(NULL);  
                   2506:     curr_time = *localtime(&rcurr_time);
1.324     brouard  2507:     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);
                   2508:     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  2509: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2510:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2511:     for (i=1;i<=n;i++) {
1.126     brouard  2512:       fprintf(ficrespow," %.12lf", p[i]);
                   2513:     }
1.239     brouard  2514:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2515:     printf("\n#model=  1      +     age ");
                   2516:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2517:     if(nagesqr==1){
1.241     brouard  2518:        printf("  + age*age  ");
                   2519:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2520:     }
                   2521:     for(j=1;j <=ncovmodel-2;j++){
                   2522:       if(Typevar[j]==0) {
                   2523:        printf("  +      V%d  ",Tvar[j]);
                   2524:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2525:       }else if(Typevar[j]==1) {
                   2526:        printf("  +    V%d*age ",Tvar[j]);
                   2527:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2528:       }else if(Typevar[j]==2) {
                   2529:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2530:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2531:       }
                   2532:     }
1.126     brouard  2533:     printf("\n");
1.239     brouard  2534: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2535: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2536:     fprintf(ficlog,"\n");
1.239     brouard  2537:     for(i=1,jk=1; i <=nlstate; i++){
                   2538:       for(k=1; k <=(nlstate+ndeath); k++){
                   2539:        if (k != i) {
                   2540:          printf("%d%d ",i,k);
                   2541:          fprintf(ficlog,"%d%d ",i,k);
                   2542:          for(j=1; j <=ncovmodel; j++){
                   2543:            printf("%12.7f ",p[jk]);
                   2544:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2545:            jk++; 
                   2546:          }
                   2547:          printf("\n");
                   2548:          fprintf(ficlog,"\n");
                   2549:        }
                   2550:       }
                   2551:     }
1.241     brouard  2552:     if(*iter <=3 && *iter >1){
1.157     brouard  2553:       tml = *localtime(&rcurr_time);
                   2554:       strcpy(strcurr,asctime(&tml));
                   2555:       rforecast_time=rcurr_time; 
1.126     brouard  2556:       itmp = strlen(strcurr);
                   2557:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2558:        strcurr[itmp-1]='\0';
1.162     brouard  2559:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2560:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2561:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2562:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2563:        forecast_time = *localtime(&rforecast_time);
                   2564:        strcpy(strfor,asctime(&forecast_time));
                   2565:        itmp = strlen(strfor);
                   2566:        if(strfor[itmp-1]=='\n')
                   2567:          strfor[itmp-1]='\0';
                   2568:        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);
                   2569:        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  2570:       }
                   2571:     }
1.187     brouard  2572:     for (i=1;i<=n;i++) { /* For each direction i */
                   2573:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2574:       fptt=(*fret); 
                   2575: #ifdef DEBUG
1.203     brouard  2576:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2577:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2578: #endif
1.203     brouard  2579:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2580:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2581: #ifdef LINMINORIGINAL
1.188     brouard  2582:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2583: #else
                   2584:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2585:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2586: #endif
                   2587:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2588:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2589:                                /* because that direction will be replaced unless the gain del is small */
                   2590:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2591:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2592:                                /* with the new direction. */
                   2593:                                del=fabs(fptt-(*fret)); 
                   2594:                                ibig=i; 
1.126     brouard  2595:       } 
                   2596: #ifdef DEBUG
                   2597:       printf("%d %.12e",i,(*fret));
                   2598:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2599:       for (j=1;j<=n;j++) {
1.224     brouard  2600:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2601:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2602:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2603:       }
                   2604:       for(j=1;j<=n;j++) {
1.225     brouard  2605:                                printf(" p(%d)=%.12e",j,p[j]);
                   2606:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2607:       }
                   2608:       printf("\n");
                   2609:       fprintf(ficlog,"\n");
                   2610: #endif
1.187     brouard  2611:     } /* end loop on each direction i */
                   2612:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2613:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2614:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2615:     for(j=1;j<=n;j++) {
                   2616:       if(flatdir[j] >0){
                   2617:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2618:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2619:       }
1.319     brouard  2620:       /* printf("\n"); */
                   2621:       /* fprintf(ficlog,"\n"); */
                   2622:     }
1.243     brouard  2623:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2624:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2625:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2626:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2627:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2628:       /* decreased of more than 3.84  */
                   2629:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2630:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2631:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2632:                        
1.188     brouard  2633:       /* Starting the program with initial values given by a former maximization will simply change */
                   2634:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2635:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2636:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2637: #ifdef DEBUG
                   2638:       int k[2],l;
                   2639:       k[0]=1;
                   2640:       k[1]=-1;
                   2641:       printf("Max: %.12e",(*func)(p));
                   2642:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2643:       for (j=1;j<=n;j++) {
                   2644:        printf(" %.12e",p[j]);
                   2645:        fprintf(ficlog," %.12e",p[j]);
                   2646:       }
                   2647:       printf("\n");
                   2648:       fprintf(ficlog,"\n");
                   2649:       for(l=0;l<=1;l++) {
                   2650:        for (j=1;j<=n;j++) {
                   2651:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2652:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2653:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2654:        }
                   2655:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2656:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2657:       }
                   2658: #endif
                   2659: 
                   2660:       free_vector(xit,1,n); 
                   2661:       free_vector(xits,1,n); 
                   2662:       free_vector(ptt,1,n); 
                   2663:       free_vector(pt,1,n); 
                   2664:       return; 
1.192     brouard  2665:     } /* enough precision */ 
1.240     brouard  2666:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2667:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2668:       ptt[j]=2.0*p[j]-pt[j]; 
                   2669:       xit[j]=p[j]-pt[j]; 
                   2670:       pt[j]=p[j]; 
                   2671:     } 
1.181     brouard  2672:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2673: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2674:                if (*iter <=4) {
1.225     brouard  2675: #else
                   2676: #endif
1.224     brouard  2677: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2678: #else
1.161     brouard  2679:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2680: #endif
1.162     brouard  2681:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2682:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2683:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2684:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2685:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2686:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2687:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2688:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2689:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2690:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2691:       /* mu² and del² are equal when f3=f1 */
                   2692:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2693:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2694:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2695:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2696: #ifdef NRCORIGINAL
                   2697:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2698: #else
                   2699:       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  2700:       t= t- del*SQR(fp-fptt);
1.183     brouard  2701: #endif
1.202     brouard  2702:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2703: #ifdef DEBUG
1.181     brouard  2704:       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);
                   2705:       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  2706:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2707:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2708:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2709:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2710:       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);
                   2711:       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);
                   2712: #endif
1.183     brouard  2713: #ifdef POWELLORIGINAL
                   2714:       if (t < 0.0) { /* Then we use it for new direction */
                   2715: #else
1.182     brouard  2716:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2717:                                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  2718:         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  2719:         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  2720:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2721:       } 
1.181     brouard  2722:       if (directest < 0.0) { /* Then we use it for new direction */
                   2723: #endif
1.191     brouard  2724: #ifdef DEBUGLINMIN
1.234     brouard  2725:        printf("Before linmin in direction P%d-P0\n",n);
                   2726:        for (j=1;j<=n;j++) {
                   2727:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2728:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2729:          if(j % ncovmodel == 0){
                   2730:            printf("\n");
                   2731:            fprintf(ficlog,"\n");
                   2732:          }
                   2733:        }
1.224     brouard  2734: #endif
                   2735: #ifdef LINMINORIGINAL
1.234     brouard  2736:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2737: #else
1.234     brouard  2738:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2739:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2740: #endif
1.234     brouard  2741:        
1.191     brouard  2742: #ifdef DEBUGLINMIN
1.234     brouard  2743:        for (j=1;j<=n;j++) { 
                   2744:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2745:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2746:          if(j % ncovmodel == 0){
                   2747:            printf("\n");
                   2748:            fprintf(ficlog,"\n");
                   2749:          }
                   2750:        }
1.224     brouard  2751: #endif
1.234     brouard  2752:        for (j=1;j<=n;j++) { 
                   2753:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2754:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2755:        }
1.224     brouard  2756: #ifdef LINMINORIGINAL
                   2757: #else
1.234     brouard  2758:        for (j=1, flatd=0;j<=n;j++) {
                   2759:          if(flatdir[j]>0)
                   2760:            flatd++;
                   2761:        }
                   2762:        if(flatd >0){
1.255     brouard  2763:          printf("%d flat directions: ",flatd);
                   2764:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2765:          for (j=1;j<=n;j++) { 
                   2766:            if(flatdir[j]>0){
                   2767:              printf("%d ",j);
                   2768:              fprintf(ficlog,"%d ",j);
                   2769:            }
                   2770:          }
                   2771:          printf("\n");
                   2772:          fprintf(ficlog,"\n");
1.319     brouard  2773: #ifdef FLATSUP
                   2774:           free_vector(xit,1,n); 
                   2775:           free_vector(xits,1,n); 
                   2776:           free_vector(ptt,1,n); 
                   2777:           free_vector(pt,1,n); 
                   2778:           return;
                   2779: #endif
1.234     brouard  2780:        }
1.191     brouard  2781: #endif
1.234     brouard  2782:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2783:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2784:        
1.126     brouard  2785: #ifdef DEBUG
1.234     brouard  2786:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2787:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2788:        for(j=1;j<=n;j++){
                   2789:          printf(" %lf",xit[j]);
                   2790:          fprintf(ficlog," %lf",xit[j]);
                   2791:        }
                   2792:        printf("\n");
                   2793:        fprintf(ficlog,"\n");
1.126     brouard  2794: #endif
1.192     brouard  2795:       } /* end of t or directest negative */
1.224     brouard  2796: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2797: #else
1.234     brouard  2798:       } /* end if (fptt < fp)  */
1.192     brouard  2799: #endif
1.225     brouard  2800: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2801:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2802: #else
1.224     brouard  2803: #endif
1.234     brouard  2804:                } /* loop iteration */ 
1.126     brouard  2805: } 
1.234     brouard  2806:   
1.126     brouard  2807: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2808:   
1.235     brouard  2809:   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  2810:   {
1.279     brouard  2811:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2812:      *   (and selected quantitative values in nres)
                   2813:      *  by left multiplying the unit
                   2814:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2815:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2816:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2817:      * or prevalence in state 1, prevalence in state 2, 0
                   2818:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2819:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2820:      * Output is prlim.
                   2821:      * Initial matrix pimij 
                   2822:      */
1.206     brouard  2823:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2824:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2825:   /*  0,                   0                  , 1} */
                   2826:   /*
                   2827:    * and after some iteration: */
                   2828:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2829:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2830:   /*  0,                   0                  , 1} */
                   2831:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2832:   /* {0.51571254859325999, 0.4842874514067399, */
                   2833:   /*  0.51326036147820708, 0.48673963852179264} */
                   2834:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2835:     
1.332     brouard  2836:     int i, ii,j,k, k1;
1.209     brouard  2837:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2838:   /* double **matprod2(); */ /* test */
1.218     brouard  2839:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2840:   double **newm;
1.209     brouard  2841:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2842:   int ncvloop=0;
1.288     brouard  2843:   int first=0;
1.169     brouard  2844:   
1.209     brouard  2845:   min=vector(1,nlstate);
                   2846:   max=vector(1,nlstate);
                   2847:   meandiff=vector(1,nlstate);
                   2848: 
1.218     brouard  2849:        /* Starting with matrix unity */
1.126     brouard  2850:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2851:     for (j=1;j<=nlstate+ndeath;j++){
                   2852:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2853:     }
1.169     brouard  2854:   
                   2855:   cov[1]=1.;
                   2856:   
                   2857:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2858:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2859:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2860:     ncvloop++;
1.126     brouard  2861:     newm=savm;
                   2862:     /* Covariates have to be included here again */
1.138     brouard  2863:     cov[2]=agefin;
1.319     brouard  2864:      if(nagesqr==1){
                   2865:       cov[3]= agefin*agefin;
                   2866:      }
1.332     brouard  2867:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2868:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2869:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2870:        if(Typevar[k1]==1){ /* A product with age */
                   2871:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2872:        }else{
                   2873:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2874:        }
                   2875:      }/* End of loop on model equation */
                   2876:      
                   2877: /* Start of old code (replaced by a loop on position in the model equation */
                   2878:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2879:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2880:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2881:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2882:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2883:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2884:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2885:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2886:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2887:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2888:     /*    *nsd=3                              (1)  (2)           (3) */
                   2889:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2890:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2891:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2892:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2893:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2894:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2895:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2896:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2897:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2898:     /*    *TvarsDpType */
                   2899:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2900:     /*    * nsd=1              (1)           (2) */
                   2901:     /*    *TvarsD[nsd]          3             2 */
                   2902:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2903:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2904:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2905:     /*    *\/ */
                   2906:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2907:     /*   /\* 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)); *\/ */
                   2908:     /* } */
                   2909:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2910:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2911:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2912:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2913:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2914:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2915:     /*   /\* 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]); *\/ */
                   2916:     /* } */
                   2917:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2918:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2919:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2920:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2921:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2922:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2923:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2924:     /*   } */
                   2925:     /*   /\* 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]); *\/ */
                   2926:     /* } */
                   2927:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2928:     /*   /\* 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]); *\/ */
                   2929:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2930:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2931:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2932:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2933:     /*         }else{ */
                   2934:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2935:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2936:     /*         } */
                   2937:     /*   }else{ */
                   2938:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2939:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2940:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2941:     /*         }else{ */
                   2942:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2943:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2944:     /*         } */
                   2945:     /*   } */
                   2946:     /* } /\* End product without age *\/ */
                   2947: /* ENd of old code */
1.138     brouard  2948:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2949:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2950:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2951:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2952:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2953:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2954:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2955:     
1.126     brouard  2956:     savm=oldm;
                   2957:     oldm=newm;
1.209     brouard  2958: 
                   2959:     for(j=1; j<=nlstate; j++){
                   2960:       max[j]=0.;
                   2961:       min[j]=1.;
                   2962:     }
                   2963:     for(i=1;i<=nlstate;i++){
                   2964:       sumnew=0;
                   2965:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2966:       for(j=1; j<=nlstate; j++){ 
                   2967:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2968:        max[j]=FMAX(max[j],prlim[i][j]);
                   2969:        min[j]=FMIN(min[j],prlim[i][j]);
                   2970:       }
                   2971:     }
                   2972: 
1.126     brouard  2973:     maxmax=0.;
1.209     brouard  2974:     for(j=1; j<=nlstate; j++){
                   2975:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2976:       maxmax=FMAX(maxmax,meandiff[j]);
                   2977:       /* 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  2978:     } /* j loop */
1.203     brouard  2979:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2980:     /* 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  2981:     if(maxmax < ftolpl){
1.209     brouard  2982:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2983:       free_vector(min,1,nlstate);
                   2984:       free_vector(max,1,nlstate);
                   2985:       free_vector(meandiff,1,nlstate);
1.126     brouard  2986:       return prlim;
                   2987:     }
1.288     brouard  2988:   } /* agefin loop */
1.208     brouard  2989:     /* After some age loop it doesn't converge */
1.288     brouard  2990:   if(!first){
                   2991:     first=1;
                   2992:     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  2993:     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);
                   2994:   }else if (first >=1 && 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:     first++;
                   2997:   }else if (first ==10){
                   2998:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   2999:     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");
                   3000:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3001:     first++;
1.288     brouard  3002:   }
                   3003: 
1.209     brouard  3004:   /* 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); */
                   3005:   free_vector(min,1,nlstate);
                   3006:   free_vector(max,1,nlstate);
                   3007:   free_vector(meandiff,1,nlstate);
1.208     brouard  3008:   
1.169     brouard  3009:   return prlim; /* should not reach here */
1.126     brouard  3010: }
                   3011: 
1.217     brouard  3012: 
                   3013:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3014: 
1.218     brouard  3015:  /* 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) */
                   3016:  /* 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  3017:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3018: {
1.264     brouard  3019:   /* 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  3020:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3021:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3022:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3023:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3024:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3025:   /* Initial matrix pimij */
                   3026:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3027:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3028:   /*  0,                   0                  , 1} */
                   3029:   /*
                   3030:    * and after some iteration: */
                   3031:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3032:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3033:   /*  0,                   0                  , 1} */
                   3034:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3035:   /* {0.51571254859325999, 0.4842874514067399, */
                   3036:   /*  0.51326036147820708, 0.48673963852179264} */
                   3037:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3038: 
1.332     brouard  3039:   int i, ii,j,k, k1;
1.247     brouard  3040:   int first=0;
1.217     brouard  3041:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3042:   /* double **matprod2(); */ /* test */
                   3043:   double **out, cov[NCOVMAX+1], **bmij();
                   3044:   double **newm;
1.218     brouard  3045:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3046:   double        **oldm, **savm;  /* for use */
                   3047: 
1.217     brouard  3048:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3049:   int ncvloop=0;
                   3050:   
                   3051:   min=vector(1,nlstate);
                   3052:   max=vector(1,nlstate);
                   3053:   meandiff=vector(1,nlstate);
                   3054: 
1.266     brouard  3055:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3056:   oldm=oldms; savm=savms;
                   3057:   
                   3058:   /* Starting with matrix unity */
                   3059:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3060:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3061:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3062:     }
                   3063:   
                   3064:   cov[1]=1.;
                   3065:   
                   3066:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3067:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3068:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3069:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3070:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3071:     ncvloop++;
1.218     brouard  3072:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3073:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3074:     /* Covariates have to be included here again */
                   3075:     cov[2]=agefin;
1.319     brouard  3076:     if(nagesqr==1){
1.217     brouard  3077:       cov[3]= agefin*agefin;;
1.319     brouard  3078:     }
1.332     brouard  3079:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3080:       if(Typevar[k1]==1){ /* A product with age */
                   3081:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3082:       }else{
1.332     brouard  3083:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3084:       }
1.332     brouard  3085:     }/* End of loop on model equation */
                   3086: 
                   3087: /* Old code */ 
                   3088: 
                   3089:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3090:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3091:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3092:     /*   /\* 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)); *\/ */
                   3093:     /* } */
                   3094:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3095:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3096:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3097:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3098:     /* /\* } *\/ */
                   3099:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3100:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3101:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3102:     /*   /\* 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]); *\/ */
                   3103:     /* } */
                   3104:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3105:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3106:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3107:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3108:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3109:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3110:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3111:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3112:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3113:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3114:     /*   } */
                   3115:     /*   /\* 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]); *\/ */
                   3116:     /* } */
                   3117:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3118:     /*   /\* 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]); *\/ */
                   3119:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3120:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3121:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3122:     /*         }else{ */
                   3123:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3124:     /*         } */
                   3125:     /*   }else{ */
                   3126:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3127:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3128:     /*         }else{ */
                   3129:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3130:     /*         } */
                   3131:     /*   } */
                   3132:     /* } */
1.217     brouard  3133:     
                   3134:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3135:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3136:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3137:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3138:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3139:                /* ij should be linked to the correct index of cov */
                   3140:                /* age and covariate values ij are in 'cov', but we need to pass
                   3141:                 * ij for the observed prevalence at age and status and covariate
                   3142:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3143:                 */
                   3144:     /* 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 *\/ */
                   3145:     /* 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 *\/ */
                   3146:     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  3147:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3148:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3149:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3150:     /*         printf("%d newm= ",i); */
                   3151:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3152:     /*           printf("%f ",newm[i][j]); */
                   3153:     /*         } */
                   3154:     /*         printf("oldm * "); */
                   3155:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3156:     /*           printf("%f ",oldm[i][j]); */
                   3157:     /*         } */
1.268     brouard  3158:     /*         printf(" bmmij "); */
1.266     brouard  3159:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3160:     /*           printf("%f ",pmmij[i][j]); */
                   3161:     /*         } */
                   3162:     /*         printf("\n"); */
                   3163:     /*   } */
                   3164:     /* } */
1.217     brouard  3165:     savm=oldm;
                   3166:     oldm=newm;
1.266     brouard  3167: 
1.217     brouard  3168:     for(j=1; j<=nlstate; j++){
                   3169:       max[j]=0.;
                   3170:       min[j]=1.;
                   3171:     }
                   3172:     for(j=1; j<=nlstate; j++){ 
                   3173:       for(i=1;i<=nlstate;i++){
1.234     brouard  3174:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3175:        bprlim[i][j]= newm[i][j];
                   3176:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3177:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3178:       }
                   3179:     }
1.218     brouard  3180:                
1.217     brouard  3181:     maxmax=0.;
                   3182:     for(i=1; i<=nlstate; i++){
1.318     brouard  3183:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3184:       maxmax=FMAX(maxmax,meandiff[i]);
                   3185:       /* 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  3186:     } /* i loop */
1.217     brouard  3187:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3188:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3189:     if(maxmax < ftolpl){
1.220     brouard  3190:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3191:       free_vector(min,1,nlstate);
                   3192:       free_vector(max,1,nlstate);
                   3193:       free_vector(meandiff,1,nlstate);
                   3194:       return bprlim;
                   3195:     }
1.288     brouard  3196:   } /* agefin loop */
1.217     brouard  3197:     /* After some age loop it doesn't converge */
1.288     brouard  3198:   if(!first){
1.247     brouard  3199:     first=1;
                   3200:     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\
                   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:   }
                   3203:   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  3204: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   3205:   /* 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); */
                   3206:   free_vector(min,1,nlstate);
                   3207:   free_vector(max,1,nlstate);
                   3208:   free_vector(meandiff,1,nlstate);
                   3209:   
                   3210:   return bprlim; /* should not reach here */
                   3211: }
                   3212: 
1.126     brouard  3213: /*************** transition probabilities ***************/ 
                   3214: 
                   3215: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3216: {
1.138     brouard  3217:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3218:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3219:      model to the ncovmodel covariates (including constant and age).
                   3220:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3221:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3222:      ncth covariate in the global vector x is given by the formula:
                   3223:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3224:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3225:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3226:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3227:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3228:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3229:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3230:   */
                   3231:   double s1, lnpijopii;
1.126     brouard  3232:   /*double t34;*/
1.164     brouard  3233:   int i,j, nc, ii, jj;
1.126     brouard  3234: 
1.223     brouard  3235:   for(i=1; i<= nlstate; i++){
                   3236:     for(j=1; j<i;j++){
                   3237:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3238:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3239:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3240:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3241:       }
                   3242:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3243:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3244:     }
                   3245:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3246:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3247:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3248:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3249:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3250:       }
                   3251:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3252:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3253:     }
                   3254:   }
1.218     brouard  3255:   
1.223     brouard  3256:   for(i=1; i<= nlstate; i++){
                   3257:     s1=0;
                   3258:     for(j=1; j<i; j++){
                   3259:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3260:       /* 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  3261:     }
                   3262:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3263:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.330     brouard  3264:       /* 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  3265:     }
                   3266:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3267:     ps[i][i]=1./(s1+1.);
                   3268:     /* Computing other pijs */
                   3269:     for(j=1; j<i; j++)
1.325     brouard  3270:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3271:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3272:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3273:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3274:   } /* end i */
1.218     brouard  3275:   
1.223     brouard  3276:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3277:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3278:       ps[ii][jj]=0;
                   3279:       ps[ii][ii]=1;
                   3280:     }
                   3281:   }
1.294     brouard  3282: 
                   3283: 
1.223     brouard  3284:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3285:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3286:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3287:   /*   } */
                   3288:   /*   printf("\n "); */
                   3289:   /* } */
                   3290:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3291:   /*
                   3292:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3293:                goto end;*/
1.266     brouard  3294:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3295: }
                   3296: 
1.218     brouard  3297: /*************** backward transition probabilities ***************/ 
                   3298: 
                   3299:  /* 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 ) */
                   3300: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3301:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3302: {
1.302     brouard  3303:   /* 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  3304:    * 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  3305:    */
1.218     brouard  3306:   int i, ii, j,k;
1.222     brouard  3307:   
                   3308:   double **out, **pmij();
                   3309:   double sumnew=0.;
1.218     brouard  3310:   double agefin;
1.292     brouard  3311:   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  3312:   double **dnewm, **dsavm, **doldm;
                   3313:   double **bbmij;
                   3314:   
1.218     brouard  3315:   doldm=ddoldms; /* global pointers */
1.222     brouard  3316:   dnewm=ddnewms;
                   3317:   dsavm=ddsavms;
1.318     brouard  3318: 
                   3319:   /* Debug */
                   3320:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3321:   agefin=cov[2];
1.268     brouard  3322:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3323:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3324:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3325:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3326: 
                   3327:   /* P_x */
1.325     brouard  3328:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3329:   /* outputs pmmij which is a stochastic matrix in row */
                   3330: 
                   3331:   /* Diag(w_x) */
1.292     brouard  3332:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3333:   sumnew=0.;
1.269     brouard  3334:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3335:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3336:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3337:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3338:   }
                   3339:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3340:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3341:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3342:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3343:     }
                   3344:   }else{
                   3345:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3346:       for (j=1;j<=nlstate+ndeath;j++)
                   3347:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3348:     }
                   3349:     /* if(sumnew <0.9){ */
                   3350:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3351:     /* } */
                   3352:   }
                   3353:   k3=0.0;  /* We put the last diagonal to 0 */
                   3354:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3355:       doldm[ii][ii]= k3;
                   3356:   }
                   3357:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3358:   
1.292     brouard  3359:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3360:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3361: 
1.292     brouard  3362:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3363:   /* 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  3364:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3365:     sumnew=0.;
1.222     brouard  3366:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3367:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3368:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3369:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3370:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3371:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3372:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3373:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3374:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3375:        /* }else */
1.268     brouard  3376:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3377:     } /*End ii */
                   3378:   } /* 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 */
                   3379: 
1.292     brouard  3380:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3381:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3382:   /* end bmij */
1.266     brouard  3383:   return ps; /*pointer is unchanged */
1.218     brouard  3384: }
1.217     brouard  3385: /*************** transition probabilities ***************/ 
                   3386: 
1.218     brouard  3387: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3388: {
                   3389:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3390:      computes the probability to be observed in state j being in state i by appying the
                   3391:      model to the ncovmodel covariates (including constant and age).
                   3392:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3393:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3394:      ncth covariate in the global vector x is given by the formula:
                   3395:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3396:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3397:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3398:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3399:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3400:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3401:   */
                   3402:   double s1, lnpijopii;
                   3403:   /*double t34;*/
                   3404:   int i,j, nc, ii, jj;
                   3405: 
1.234     brouard  3406:   for(i=1; i<= nlstate; i++){
                   3407:     for(j=1; j<i;j++){
                   3408:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3409:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3410:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3411:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3412:       }
                   3413:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3414:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3415:     }
                   3416:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3417:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3418:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3419:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3420:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3421:       }
                   3422:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3423:     }
                   3424:   }
                   3425:   
                   3426:   for(i=1; i<= nlstate; i++){
                   3427:     s1=0;
                   3428:     for(j=1; j<i; j++){
                   3429:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3430:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3431:     }
                   3432:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3433:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3434:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3435:     }
                   3436:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3437:     ps[i][i]=1./(s1+1.);
                   3438:     /* Computing other pijs */
                   3439:     for(j=1; j<i; j++)
                   3440:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3441:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3442:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3443:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3444:   } /* end i */
                   3445:   
                   3446:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3447:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3448:       ps[ii][jj]=0;
                   3449:       ps[ii][ii]=1;
                   3450:     }
                   3451:   }
1.296     brouard  3452:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3453:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3454:     s1=0.;
                   3455:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3456:       s1+=ps[ii][jj];
                   3457:     }
                   3458:     for(ii=1; ii<= nlstate; ii++){
                   3459:       ps[ii][jj]=ps[ii][jj]/s1;
                   3460:     }
                   3461:   }
                   3462:   /* Transposition */
                   3463:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3464:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3465:       s1=ps[ii][jj];
                   3466:       ps[ii][jj]=ps[jj][ii];
                   3467:       ps[jj][ii]=s1;
                   3468:     }
                   3469:   }
                   3470:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3471:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3472:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3473:   /*   } */
                   3474:   /*   printf("\n "); */
                   3475:   /* } */
                   3476:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3477:   /*
                   3478:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3479:     goto end;*/
                   3480:   return ps;
1.217     brouard  3481: }
                   3482: 
                   3483: 
1.126     brouard  3484: /**************** Product of 2 matrices ******************/
                   3485: 
1.145     brouard  3486: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3487: {
                   3488:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3489:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3490:   /* in, b, out are matrice of pointers which should have been initialized 
                   3491:      before: only the contents of out is modified. The function returns
                   3492:      a pointer to pointers identical to out */
1.145     brouard  3493:   int i, j, k;
1.126     brouard  3494:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3495:     for(k=ncolol; k<=ncoloh; k++){
                   3496:       out[i][k]=0.;
                   3497:       for(j=ncl; j<=nch; j++)
                   3498:        out[i][k] +=in[i][j]*b[j][k];
                   3499:     }
1.126     brouard  3500:   return out;
                   3501: }
                   3502: 
                   3503: 
                   3504: /************* Higher Matrix Product ***************/
                   3505: 
1.235     brouard  3506: 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  3507: {
1.332     brouard  3508:   /* 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  3509:      'nhstepm*hstepm*stepm' months (i.e. until
                   3510:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3511:      nhstepm*hstepm matrices. 
                   3512:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3513:      (typically every 2 years instead of every month which is too big 
                   3514:      for the memory).
                   3515:      Model is determined by parameters x and covariates have to be 
                   3516:      included manually here. 
                   3517: 
                   3518:      */
                   3519: 
1.330     brouard  3520:   int i, j, d, h, k, k1;
1.131     brouard  3521:   double **out, cov[NCOVMAX+1];
1.126     brouard  3522:   double **newm;
1.187     brouard  3523:   double agexact;
1.214     brouard  3524:   double agebegin, ageend;
1.126     brouard  3525: 
                   3526:   /* Hstepm could be zero and should return the unit matrix */
                   3527:   for (i=1;i<=nlstate+ndeath;i++)
                   3528:     for (j=1;j<=nlstate+ndeath;j++){
                   3529:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3530:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3531:     }
                   3532:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3533:   for(h=1; h <=nhstepm; h++){
                   3534:     for(d=1; d <=hstepm; d++){
                   3535:       newm=savm;
                   3536:       /* Covariates have to be included here again */
                   3537:       cov[1]=1.;
1.214     brouard  3538:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3539:       cov[2]=agexact;
1.319     brouard  3540:       if(nagesqr==1){
1.227     brouard  3541:        cov[3]= agexact*agexact;
1.319     brouard  3542:       }
1.330     brouard  3543:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3544:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3545:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3546:        if(Typevar[k1]==1){ /* A product with age */
                   3547:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3548:        }else{
                   3549:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3550:        }
                   3551:       }/* End of loop on model equation */
                   3552:        /* Old code */ 
                   3553: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3554: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3555: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3556: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3557: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3558: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3559: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3560: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3561: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3562: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3563: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3564: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3565: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3566: /*       /\* 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]])); *\/ */
                   3567: /*       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); */
                   3568: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3569: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3570: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3571: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3572: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3573: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3574: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3575: /*       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]]); */
                   3576: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3577: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3578: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3579: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3580: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3581: /*       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]); */
                   3582: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3583: 
                   3584: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3585: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3586: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3587: /*       /\* *\/ */
1.330     brouard  3588: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3589: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3590: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3591: /* /\*cptcovage=2                   1               2      *\/ */
                   3592: /* /\*Tage[k]=                      5               8      *\/  */
                   3593: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3594: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3595: /*       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]]); */
                   3596: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3597: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3598: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3599: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3600: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3601: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3602: /*       /\*   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); *\/ */
                   3603: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3604: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3605: /*       /\* } *\/ */
                   3606: /*       /\* 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]); *\/ */
                   3607: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3608: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3609: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3610: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3611: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3612: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3613: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3614: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3615: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3616:          
1.332     brouard  3617: /*       /\* 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])]); *\/ */
                   3618: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3619: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3620: /*       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]]); */
                   3621: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3622: 
                   3623: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3624: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3625: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3626: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3627: /*           /\* 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]])]; *\/ */
                   3628: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3629: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3630: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3631: /*       /\*   } *\/ */
                   3632: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3633: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3634: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3635: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3636: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3637: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3638: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3639: /*       /\*   } *\/ */
                   3640: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3641: /*     }/\*end of products *\/ */
                   3642:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3643:       /* for (k=1; k<=cptcovn;k++)  */
                   3644:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3645:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3646:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3647:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3648:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3649:       
                   3650:       
1.126     brouard  3651:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3652:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3653:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3654:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3655:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3656:       /* if((int)age == 70){ */
                   3657:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3658:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3659:       /*         printf("%d pmmij ",i); */
                   3660:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3661:       /*           printf("%f ",pmmij[i][j]); */
                   3662:       /*         } */
                   3663:       /*         printf(" oldm "); */
                   3664:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3665:       /*           printf("%f ",oldm[i][j]); */
                   3666:       /*         } */
                   3667:       /*         printf("\n"); */
                   3668:       /*       } */
                   3669:       /* } */
1.126     brouard  3670:       savm=oldm;
                   3671:       oldm=newm;
                   3672:     }
                   3673:     for(i=1; i<=nlstate+ndeath; i++)
                   3674:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3675:        po[i][j][h]=newm[i][j];
                   3676:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3677:       }
1.128     brouard  3678:     /*printf("h=%d ",h);*/
1.126     brouard  3679:   } /* end h */
1.267     brouard  3680:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3681:   return po;
                   3682: }
                   3683: 
1.217     brouard  3684: /************* Higher Back Matrix Product ***************/
1.218     brouard  3685: /* 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  3686: 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  3687: {
1.332     brouard  3688:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3689:      computes the transition matrix starting at age 'age' over
1.217     brouard  3690:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3691:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3692:      nhstepm*hstepm matrices.
                   3693:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3694:      (typically every 2 years instead of every month which is too big
1.217     brouard  3695:      for the memory).
1.218     brouard  3696:      Model is determined by parameters x and covariates have to be
1.266     brouard  3697:      included manually here. Then we use a call to bmij(x and cov)
                   3698:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3699:   */
1.217     brouard  3700: 
1.332     brouard  3701:   int i, j, d, h, k, k1;
1.266     brouard  3702:   double **out, cov[NCOVMAX+1], **bmij();
                   3703:   double **newm, ***newmm;
1.217     brouard  3704:   double agexact;
                   3705:   double agebegin, ageend;
1.222     brouard  3706:   double **oldm, **savm;
1.217     brouard  3707: 
1.266     brouard  3708:   newmm=po; /* To be saved */
                   3709:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3710:   /* Hstepm could be zero and should return the unit matrix */
                   3711:   for (i=1;i<=nlstate+ndeath;i++)
                   3712:     for (j=1;j<=nlstate+ndeath;j++){
                   3713:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3714:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3715:     }
                   3716:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3717:   for(h=1; h <=nhstepm; h++){
                   3718:     for(d=1; d <=hstepm; d++){
                   3719:       newm=savm;
                   3720:       /* Covariates have to be included here again */
                   3721:       cov[1]=1.;
1.271     brouard  3722:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3723:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3724:         /* Debug */
                   3725:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3726:       cov[2]=agexact;
1.332     brouard  3727:       if(nagesqr==1){
1.222     brouard  3728:        cov[3]= agexact*agexact;
1.332     brouard  3729:       }
                   3730:       /** New code */
                   3731:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3732:        if(Typevar[k1]==1){ /* A product with age */
                   3733:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3734:        }else{
1.332     brouard  3735:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3736:        }
1.332     brouard  3737:       }/* End of loop on model equation */
                   3738:       /** End of new code */
                   3739:   /** This was old code */
                   3740:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3741:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3742:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3743:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3744:       /*   /\* 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)); *\/ */
                   3745:       /* } */
                   3746:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3747:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3748:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3749:       /*       /\* 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]); *\/ */
                   3750:       /* } */
                   3751:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3752:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3753:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3754:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3755:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3756:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3757:       /*       } */
                   3758:       /*       /\* 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]); *\/ */
                   3759:       /* } */
                   3760:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3761:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3762:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3763:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3764:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3765:       /*         }else{ */
                   3766:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3767:       /*         } */
                   3768:       /*       }else{ */
                   3769:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3770:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3771:       /*         }else{ */
                   3772:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3773:       /*         } */
                   3774:       /*       } */
                   3775:       /* }                      */
                   3776:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3777:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3778: /** End of old code */
                   3779:       
1.218     brouard  3780:       /* Careful transposed matrix */
1.266     brouard  3781:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3782:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3783:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3784:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3785:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3786:       /* if((int)age == 70){ */
                   3787:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3788:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3789:       /*         printf("%d pmmij ",i); */
                   3790:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3791:       /*           printf("%f ",pmmij[i][j]); */
                   3792:       /*         } */
                   3793:       /*         printf(" oldm "); */
                   3794:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3795:       /*           printf("%f ",oldm[i][j]); */
                   3796:       /*         } */
                   3797:       /*         printf("\n"); */
                   3798:       /*       } */
                   3799:       /* } */
                   3800:       savm=oldm;
                   3801:       oldm=newm;
                   3802:     }
                   3803:     for(i=1; i<=nlstate+ndeath; i++)
                   3804:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3805:        po[i][j][h]=newm[i][j];
1.268     brouard  3806:        /* if(h==nhstepm) */
                   3807:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3808:       }
1.268     brouard  3809:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3810:   } /* end h */
1.268     brouard  3811:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3812:   return po;
                   3813: }
                   3814: 
                   3815: 
1.162     brouard  3816: #ifdef NLOPT
                   3817:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3818:   double fret;
                   3819:   double *xt;
                   3820:   int j;
                   3821:   myfunc_data *d2 = (myfunc_data *) pd;
                   3822: /* xt = (p1-1); */
                   3823:   xt=vector(1,n); 
                   3824:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3825: 
                   3826:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3827:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3828:   printf("Function = %.12lf ",fret);
                   3829:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3830:   printf("\n");
                   3831:  free_vector(xt,1,n);
                   3832:   return fret;
                   3833: }
                   3834: #endif
1.126     brouard  3835: 
                   3836: /*************** log-likelihood *************/
                   3837: double func( double *x)
                   3838: {
1.226     brouard  3839:   int i, ii, j, k, mi, d, kk;
                   3840:   int ioffset=0;
                   3841:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3842:   double **out;
                   3843:   double lli; /* Individual log likelihood */
                   3844:   int s1, s2;
1.228     brouard  3845:   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  3846:   double bbh, survp;
                   3847:   long ipmx;
                   3848:   double agexact;
                   3849:   /*extern weight */
                   3850:   /* We are differentiating ll according to initial status */
                   3851:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3852:   /*for(i=1;i<imx;i++) 
                   3853:     printf(" %d\n",s[4][i]);
                   3854:   */
1.162     brouard  3855: 
1.226     brouard  3856:   ++countcallfunc;
1.162     brouard  3857: 
1.226     brouard  3858:   cov[1]=1.;
1.126     brouard  3859: 
1.226     brouard  3860:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3861:   ioffset=0;
1.226     brouard  3862:   if(mle==1){
                   3863:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3864:       /* Computes the values of the ncovmodel covariates of the model
                   3865:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3866:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3867:         to be observed in j being in i according to the model.
                   3868:       */
1.243     brouard  3869:       ioffset=2+nagesqr ;
1.233     brouard  3870:    /* Fixed */
1.319     brouard  3871:       for (k=1; k<=ncovf;k++){ /* For each fixed covariate dummu or quant or prod */
                   3872:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3873:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3874:        /*  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  3875:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.319     brouard  3876:        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)*/
                   3877:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3878:       }
1.226     brouard  3879:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3880:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3881:         has been calculated etc */
                   3882:       /* For an individual i, wav[i] gives the number of effective waves */
                   3883:       /* We compute the contribution to Likelihood of each effective transition
                   3884:         mw[mi][i] is real wave of the mi th effectve wave */
                   3885:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3886:         s2=s[mw[mi+1][i]][i];
                   3887:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3888:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3889:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3890:       */
                   3891:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  3892:        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*/
                   3893:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? */
1.242     brouard  3894:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3895:        }
                   3896:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3897:          for (j=1;j<=nlstate+ndeath;j++){
                   3898:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3899:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3900:          }
                   3901:        for(d=0; d<dh[mi][i]; d++){
                   3902:          newm=savm;
                   3903:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3904:          cov[2]=agexact;
                   3905:          if(nagesqr==1)
                   3906:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3907:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3908:            if(!FixedV[Tvar[Tage[kk]]])
                   3909:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3910:            else
                   3911:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3912:          }
                   3913:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3914:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3915:          savm=oldm;
                   3916:          oldm=newm;
                   3917:        } /* end mult */
                   3918:        
                   3919:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3920:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3921:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3922:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3923:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3924:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3925:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3926:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3927:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3928:                                 * -stepm/2 to stepm/2 .
                   3929:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3930:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3931:                                 */
1.234     brouard  3932:        s1=s[mw[mi][i]][i];
                   3933:        s2=s[mw[mi+1][i]][i];
                   3934:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3935:        /* bias bh is positive if real duration
                   3936:         * is higher than the multiple of stepm and negative otherwise.
                   3937:         */
                   3938:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3939:        if( s2 > nlstate){ 
                   3940:          /* i.e. if s2 is a death state and if the date of death is known 
                   3941:             then the contribution to the likelihood is the probability to 
                   3942:             die between last step unit time and current  step unit time, 
                   3943:             which is also equal to probability to die before dh 
                   3944:             minus probability to die before dh-stepm . 
                   3945:             In version up to 0.92 likelihood was computed
                   3946:             as if date of death was unknown. Death was treated as any other
                   3947:             health state: the date of the interview describes the actual state
                   3948:             and not the date of a change in health state. The former idea was
                   3949:             to consider that at each interview the state was recorded
                   3950:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3951:             introduced the exact date of death then we should have modified
                   3952:             the contribution of an exact death to the likelihood. This new
                   3953:             contribution is smaller and very dependent of the step unit
                   3954:             stepm. It is no more the probability to die between last interview
                   3955:             and month of death but the probability to survive from last
                   3956:             interview up to one month before death multiplied by the
                   3957:             probability to die within a month. Thanks to Chris
                   3958:             Jackson for correcting this bug.  Former versions increased
                   3959:             mortality artificially. The bad side is that we add another loop
                   3960:             which slows down the processing. The difference can be up to 10%
                   3961:             lower mortality.
                   3962:          */
                   3963:          /* If, at the beginning of the maximization mostly, the
                   3964:             cumulative probability or probability to be dead is
                   3965:             constant (ie = 1) over time d, the difference is equal to
                   3966:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3967:             s1 at precedent wave, to be dead a month before current
                   3968:             wave is equal to probability, being at state s1 at
                   3969:             precedent wave, to be dead at mont of the current
                   3970:             wave. Then the observed probability (that this person died)
                   3971:             is null according to current estimated parameter. In fact,
                   3972:             it should be very low but not zero otherwise the log go to
                   3973:             infinity.
                   3974:          */
1.183     brouard  3975: /* #ifdef INFINITYORIGINAL */
                   3976: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3977: /* #else */
                   3978: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3979: /*         lli=log(mytinydouble); */
                   3980: /*       else */
                   3981: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3982: /* #endif */
1.226     brouard  3983:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3984:          
1.226     brouard  3985:        } else if  ( s2==-1 ) { /* alive */
                   3986:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3987:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3988:          /*survp += out[s1][j]; */
                   3989:          lli= log(survp);
                   3990:        }
                   3991:        else if  (s2==-4) { 
                   3992:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3993:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3994:          lli= log(survp); 
                   3995:        } 
                   3996:        else if  (s2==-5) { 
                   3997:          for (j=1,survp=0. ; j<=2; j++)  
                   3998:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3999:          lli= log(survp); 
                   4000:        } 
                   4001:        else{
                   4002:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4003:          /*  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 */
                   4004:        } 
                   4005:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4006:        /*if(lli ==000.0)*/
                   4007:        /*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); */
                   4008:        ipmx +=1;
                   4009:        sw += weight[i];
                   4010:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4011:        /* if (lli < log(mytinydouble)){ */
                   4012:        /*   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); */
                   4013:        /*   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]); */
                   4014:        /* } */
                   4015:       } /* end of wave */
                   4016:     } /* end of individual */
                   4017:   }  else if(mle==2){
                   4018:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4019:       ioffset=2+nagesqr ;
                   4020:       for (k=1; k<=ncovf;k++)
                   4021:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4022:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4023:        for(k=1; k <= ncovv ; k++){
                   4024:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4025:        }
1.226     brouard  4026:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4027:          for (j=1;j<=nlstate+ndeath;j++){
                   4028:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4029:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4030:          }
                   4031:        for(d=0; d<=dh[mi][i]; d++){
                   4032:          newm=savm;
                   4033:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4034:          cov[2]=agexact;
                   4035:          if(nagesqr==1)
                   4036:            cov[3]= agexact*agexact;
                   4037:          for (kk=1; kk<=cptcovage;kk++) {
                   4038:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4039:          }
                   4040:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4041:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4042:          savm=oldm;
                   4043:          oldm=newm;
                   4044:        } /* end mult */
                   4045:       
                   4046:        s1=s[mw[mi][i]][i];
                   4047:        s2=s[mw[mi+1][i]][i];
                   4048:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4049:        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 */
                   4050:        ipmx +=1;
                   4051:        sw += weight[i];
                   4052:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4053:       } /* end of wave */
                   4054:     } /* end of individual */
                   4055:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4056:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4057:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4058:       for(mi=1; mi<= wav[i]-1; mi++){
                   4059:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4060:          for (j=1;j<=nlstate+ndeath;j++){
                   4061:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4062:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4063:          }
                   4064:        for(d=0; d<dh[mi][i]; d++){
                   4065:          newm=savm;
                   4066:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4067:          cov[2]=agexact;
                   4068:          if(nagesqr==1)
                   4069:            cov[3]= agexact*agexact;
                   4070:          for (kk=1; kk<=cptcovage;kk++) {
                   4071:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4072:          }
                   4073:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4074:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4075:          savm=oldm;
                   4076:          oldm=newm;
                   4077:        } /* end mult */
                   4078:       
                   4079:        s1=s[mw[mi][i]][i];
                   4080:        s2=s[mw[mi+1][i]][i];
                   4081:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4082:        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 */
                   4083:        ipmx +=1;
                   4084:        sw += weight[i];
                   4085:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4086:       } /* end of wave */
                   4087:     } /* end of individual */
                   4088:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4089:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4090:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4091:       for(mi=1; mi<= wav[i]-1; mi++){
                   4092:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4093:          for (j=1;j<=nlstate+ndeath;j++){
                   4094:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4095:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4096:          }
                   4097:        for(d=0; d<dh[mi][i]; d++){
                   4098:          newm=savm;
                   4099:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4100:          cov[2]=agexact;
                   4101:          if(nagesqr==1)
                   4102:            cov[3]= agexact*agexact;
                   4103:          for (kk=1; kk<=cptcovage;kk++) {
                   4104:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4105:          }
1.126     brouard  4106:        
1.226     brouard  4107:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4108:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4109:          savm=oldm;
                   4110:          oldm=newm;
                   4111:        } /* end mult */
                   4112:       
                   4113:        s1=s[mw[mi][i]][i];
                   4114:        s2=s[mw[mi+1][i]][i];
                   4115:        if( s2 > nlstate){ 
                   4116:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4117:        } else if  ( s2==-1 ) { /* alive */
                   4118:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4119:            survp += out[s1][j];
                   4120:          lli= log(survp);
                   4121:        }else{
                   4122:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4123:        }
                   4124:        ipmx +=1;
                   4125:        sw += weight[i];
                   4126:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4127: /*     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  4128:       } /* end of wave */
                   4129:     } /* end of individual */
                   4130:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4131:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4132:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4133:       for(mi=1; mi<= wav[i]-1; mi++){
                   4134:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4135:          for (j=1;j<=nlstate+ndeath;j++){
                   4136:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4137:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4138:          }
                   4139:        for(d=0; d<dh[mi][i]; d++){
                   4140:          newm=savm;
                   4141:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4142:          cov[2]=agexact;
                   4143:          if(nagesqr==1)
                   4144:            cov[3]= agexact*agexact;
                   4145:          for (kk=1; kk<=cptcovage;kk++) {
                   4146:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4147:          }
1.126     brouard  4148:        
1.226     brouard  4149:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4150:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4151:          savm=oldm;
                   4152:          oldm=newm;
                   4153:        } /* end mult */
                   4154:       
                   4155:        s1=s[mw[mi][i]][i];
                   4156:        s2=s[mw[mi+1][i]][i];
                   4157:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4158:        ipmx +=1;
                   4159:        sw += weight[i];
                   4160:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4161:        /*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]);*/
                   4162:       } /* end of wave */
                   4163:     } /* end of individual */
                   4164:   } /* End of if */
                   4165:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4166:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4167:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4168:   return -l;
1.126     brouard  4169: }
                   4170: 
                   4171: /*************** log-likelihood *************/
                   4172: double funcone( double *x)
                   4173: {
1.228     brouard  4174:   /* Same as func but slower because of a lot of printf and if */
1.335   ! brouard  4175:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4176:   int ioffset=0;
1.131     brouard  4177:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4178:   double **out;
                   4179:   double lli; /* Individual log likelihood */
                   4180:   double llt;
                   4181:   int s1, s2;
1.228     brouard  4182:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4183: 
1.126     brouard  4184:   double bbh, survp;
1.187     brouard  4185:   double agexact;
1.214     brouard  4186:   double agebegin, ageend;
1.126     brouard  4187:   /*extern weight */
                   4188:   /* We are differentiating ll according to initial status */
                   4189:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4190:   /*for(i=1;i<imx;i++) 
                   4191:     printf(" %d\n",s[4][i]);
                   4192:   */
                   4193:   cov[1]=1.;
                   4194: 
                   4195:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4196:   ioffset=0;
                   4197:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  4198:     /* ioffset=2+nagesqr+cptcovage; */
                   4199:     ioffset=2+nagesqr;
1.232     brouard  4200:     /* Fixed */
1.224     brouard  4201:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4202:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335   ! brouard  4203:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
        !          4204:       cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
1.232     brouard  4205: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4206: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4207: /*    cov[2+6]=covar[2][i]; V2  */
                   4208: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4209: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4210: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4211: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4212: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4213: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4214:     }
1.232     brouard  4215:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4216:     /*   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?)*\/ */
                   4217:     /* } */
1.231     brouard  4218:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4219:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4220:     /* } */
1.225     brouard  4221:     
1.233     brouard  4222: 
                   4223:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  4224:     /* Wave varying (but not age varying) */
                   4225:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  4226:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   4227:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4228:       }
1.232     brouard  4229:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  4230:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4231:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4232:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4233:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4234:       /* 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  4235:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4236:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4237:       /*       /\* 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]); *\/ */
                   4238:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4239:       /* } */
1.126     brouard  4240:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4241:        for (j=1;j<=nlstate+ndeath;j++){
                   4242:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4243:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4244:        }
1.214     brouard  4245:       
                   4246:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4247:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4248:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4249:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4250:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4251:          and mw[mi+1][i]. dh depends on stepm.*/
                   4252:        newm=savm;
1.247     brouard  4253:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4254:        cov[2]=agexact;
                   4255:        if(nagesqr==1)
                   4256:          cov[3]= agexact*agexact;
                   4257:        for (kk=1; kk<=cptcovage;kk++) {
                   4258:          if(!FixedV[Tvar[Tage[kk]]])
                   4259:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4260:          else
                   4261:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   4262:        }
                   4263:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4264:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4265:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4266:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4267:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4268:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4269:        savm=oldm;
                   4270:        oldm=newm;
1.126     brouard  4271:       } /* end mult */
                   4272:       
                   4273:       s1=s[mw[mi][i]][i];
                   4274:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4275:       /* if(s2==-1){ */
1.268     brouard  4276:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4277:       /*       /\* exit(1); *\/ */
                   4278:       /* } */
1.126     brouard  4279:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4280:       /* bias is positive if real duration
                   4281:        * is higher than the multiple of stepm and negative otherwise.
                   4282:        */
                   4283:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4284:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4285:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4286:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4287:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4288:        lli= log(survp);
1.126     brouard  4289:       }else if (mle==1){
1.242     brouard  4290:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4291:       } else if(mle==2){
1.242     brouard  4292:        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  4293:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4294:        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  4295:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4296:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4297:       } else{  /* mle=0 back to 1 */
1.242     brouard  4298:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4299:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4300:       } /* End of if */
                   4301:       ipmx +=1;
                   4302:       sw += weight[i];
                   4303:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.335   ! brouard  4304:       /* printf("Funcone i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4305:       if(globpr){
1.246     brouard  4306:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4307:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4308:                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  4309:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335   ! brouard  4310:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
        !          4311:  /* %11.6f %11.6f %11.6f ", \ */
        !          4312:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
        !          4313:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4314:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4315:          llt +=ll[k]*gipmx/gsw;
                   4316:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335   ! brouard  4317:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4318:        }
                   4319:        fprintf(ficresilk," %10.6f\n", -llt);
1.335   ! brouard  4320:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4321:       }
1.335   ! brouard  4322:     } /* end of wave */
        !          4323:   } /* end of individual */
        !          4324:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4325: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335   ! brouard  4326:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          4327:   if(globpr==0){ /* First time we count the contributions and weights */
        !          4328:     gipmx=ipmx;
        !          4329:     gsw=sw;
        !          4330:   }
1.232     brouard  4331: return -l;
1.126     brouard  4332: }
                   4333: 
                   4334: 
                   4335: /*************** function likelione ***********/
1.292     brouard  4336: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4337: {
                   4338:   /* This routine should help understanding what is done with 
                   4339:      the selection of individuals/waves and
                   4340:      to check the exact contribution to the likelihood.
                   4341:      Plotting could be done.
                   4342:    */
                   4343:   int k;
                   4344: 
                   4345:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4346:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4347:     strcat(fileresilk,fileresu);
1.126     brouard  4348:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4349:       printf("Problem with resultfile: %s\n", fileresilk);
                   4350:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4351:     }
1.214     brouard  4352:     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");
                   4353:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4354:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4355:     for(k=1; k<=nlstate; k++) 
                   4356:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4357:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4358:   }
                   4359: 
1.292     brouard  4360:   *fretone=(*func)(p);
1.126     brouard  4361:   if(*globpri !=0){
                   4362:     fclose(ficresilk);
1.205     brouard  4363:     if (mle ==0)
                   4364:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4365:     else if(mle >=1)
                   4366:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4367:     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  4368:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4369:       
                   4370:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4371:       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  4372: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4373:     }
1.207     brouard  4374:     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  4375: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4376:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4377: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4378:     fflush(fichtm);
1.205     brouard  4379:   }
1.126     brouard  4380:   return;
                   4381: }
                   4382: 
                   4383: 
                   4384: /*********** Maximum Likelihood Estimation ***************/
                   4385: 
                   4386: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4387: {
1.319     brouard  4388:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4389:   double **xi;
                   4390:   double fret;
                   4391:   double fretone; /* Only one call to likelihood */
                   4392:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4393: 
                   4394: #ifdef NLOPT
                   4395:   int creturn;
                   4396:   nlopt_opt opt;
                   4397:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4398:   double *lb;
                   4399:   double minf; /* the minimum objective value, upon return */
                   4400:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4401:   myfunc_data dinst, *d = &dinst;
                   4402: #endif
                   4403: 
                   4404: 
1.126     brouard  4405:   xi=matrix(1,npar,1,npar);
                   4406:   for (i=1;i<=npar;i++)
                   4407:     for (j=1;j<=npar;j++)
                   4408:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4409:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4410:   strcpy(filerespow,"POW_"); 
1.126     brouard  4411:   strcat(filerespow,fileres);
                   4412:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4413:     printf("Problem with resultfile: %s\n", filerespow);
                   4414:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4415:   }
                   4416:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4417:   for (i=1;i<=nlstate;i++)
                   4418:     for(j=1;j<=nlstate+ndeath;j++)
                   4419:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4420:   fprintf(ficrespow,"\n");
1.162     brouard  4421: #ifdef POWELL
1.319     brouard  4422: #ifdef LINMINORIGINAL
                   4423: #else /* LINMINORIGINAL */
                   4424:   
                   4425:   flatdir=ivector(1,npar); 
                   4426:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4427: #endif /*LINMINORIGINAL */
                   4428: 
                   4429: #ifdef FLATSUP
                   4430:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4431:   /* reorganizing p by suppressing flat directions */
                   4432:   for(i=1, jk=1; i <=nlstate; i++){
                   4433:     for(k=1; k <=(nlstate+ndeath); k++){
                   4434:       if (k != i) {
                   4435:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4436:         if(flatdir[jk]==1){
                   4437:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4438:         }
                   4439:         for(j=1; j <=ncovmodel; j++){
                   4440:           printf("%12.7f ",p[jk]);
                   4441:           jk++; 
                   4442:         }
                   4443:         printf("\n");
                   4444:       }
                   4445:     }
                   4446:   }
                   4447: /* skipping */
                   4448:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4449:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4450:     for(k=1; k <=(nlstate+ndeath); k++){
                   4451:       if (k != i) {
                   4452:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4453:         if(flatdir[jk]==1){
                   4454:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4455:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4456:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4457:             /*q[jjk]=p[jk];*/
                   4458:           }
                   4459:         }else{
                   4460:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4461:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4462:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4463:             /*q[jjk]=p[jk];*/
                   4464:           }
                   4465:         }
                   4466:         printf("\n");
                   4467:       }
                   4468:       fflush(stdout);
                   4469:     }
                   4470:   }
                   4471:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4472: #else  /* FLATSUP */
1.126     brouard  4473:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4474: #endif  /* FLATSUP */
                   4475: 
                   4476: #ifdef LINMINORIGINAL
                   4477: #else
                   4478:       free_ivector(flatdir,1,npar); 
                   4479: #endif  /* LINMINORIGINAL*/
                   4480: #endif /* POWELL */
1.126     brouard  4481: 
1.162     brouard  4482: #ifdef NLOPT
                   4483: #ifdef NEWUOA
                   4484:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4485: #else
                   4486:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4487: #endif
                   4488:   lb=vector(0,npar-1);
                   4489:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4490:   nlopt_set_lower_bounds(opt, lb);
                   4491:   nlopt_set_initial_step1(opt, 0.1);
                   4492:   
                   4493:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4494:   d->function = func;
                   4495:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4496:   nlopt_set_min_objective(opt, myfunc, d);
                   4497:   nlopt_set_xtol_rel(opt, ftol);
                   4498:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4499:     printf("nlopt failed! %d\n",creturn); 
                   4500:   }
                   4501:   else {
                   4502:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4503:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4504:     iter=1; /* not equal */
                   4505:   }
                   4506:   nlopt_destroy(opt);
                   4507: #endif
1.319     brouard  4508: #ifdef FLATSUP
                   4509:   /* npared = npar -flatd/ncovmodel; */
                   4510:   /* xired= matrix(1,npared,1,npared); */
                   4511:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4512:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4513:   /* free_matrix(xire,1,npared,1,npared); */
                   4514: #else  /* FLATSUP */
                   4515: #endif /* FLATSUP */
1.126     brouard  4516:   free_matrix(xi,1,npar,1,npar);
                   4517:   fclose(ficrespow);
1.203     brouard  4518:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4519:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4520:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4521: 
                   4522: }
                   4523: 
                   4524: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4525: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4526: {
                   4527:   double  **a,**y,*x,pd;
1.203     brouard  4528:   /* double **hess; */
1.164     brouard  4529:   int i, j;
1.126     brouard  4530:   int *indx;
                   4531: 
                   4532:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4533:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4534:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4535:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4536:   double gompertz(double p[]);
1.203     brouard  4537:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4538: 
                   4539:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4540:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4541:   for (i=1;i<=npar;i++){
1.203     brouard  4542:     printf("%d-",i);fflush(stdout);
                   4543:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4544:    
                   4545:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4546:     
                   4547:     /*  printf(" %f ",p[i]);
                   4548:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4549:   }
                   4550:   
                   4551:   for (i=1;i<=npar;i++) {
                   4552:     for (j=1;j<=npar;j++)  {
                   4553:       if (j>i) { 
1.203     brouard  4554:        printf(".%d-%d",i,j);fflush(stdout);
                   4555:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4556:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4557:        
                   4558:        hess[j][i]=hess[i][j];    
                   4559:        /*printf(" %lf ",hess[i][j]);*/
                   4560:       }
                   4561:     }
                   4562:   }
                   4563:   printf("\n");
                   4564:   fprintf(ficlog,"\n");
                   4565: 
                   4566:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4567:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4568:   
                   4569:   a=matrix(1,npar,1,npar);
                   4570:   y=matrix(1,npar,1,npar);
                   4571:   x=vector(1,npar);
                   4572:   indx=ivector(1,npar);
                   4573:   for (i=1;i<=npar;i++)
                   4574:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4575:   ludcmp(a,npar,indx,&pd);
                   4576: 
                   4577:   for (j=1;j<=npar;j++) {
                   4578:     for (i=1;i<=npar;i++) x[i]=0;
                   4579:     x[j]=1;
                   4580:     lubksb(a,npar,indx,x);
                   4581:     for (i=1;i<=npar;i++){ 
                   4582:       matcov[i][j]=x[i];
                   4583:     }
                   4584:   }
                   4585: 
                   4586:   printf("\n#Hessian matrix#\n");
                   4587:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4588:   for (i=1;i<=npar;i++) { 
                   4589:     for (j=1;j<=npar;j++) { 
1.203     brouard  4590:       printf("%.6e ",hess[i][j]);
                   4591:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4592:     }
                   4593:     printf("\n");
                   4594:     fprintf(ficlog,"\n");
                   4595:   }
                   4596: 
1.203     brouard  4597:   /* printf("\n#Covariance matrix#\n"); */
                   4598:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4599:   /* for (i=1;i<=npar;i++) {  */
                   4600:   /*   for (j=1;j<=npar;j++) {  */
                   4601:   /*     printf("%.6e ",matcov[i][j]); */
                   4602:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4603:   /*   } */
                   4604:   /*   printf("\n"); */
                   4605:   /*   fprintf(ficlog,"\n"); */
                   4606:   /* } */
                   4607: 
1.126     brouard  4608:   /* Recompute Inverse */
1.203     brouard  4609:   /* for (i=1;i<=npar;i++) */
                   4610:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4611:   /* ludcmp(a,npar,indx,&pd); */
                   4612: 
                   4613:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4614: 
                   4615:   /* for (j=1;j<=npar;j++) { */
                   4616:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4617:   /*   x[j]=1; */
                   4618:   /*   lubksb(a,npar,indx,x); */
                   4619:   /*   for (i=1;i<=npar;i++){  */
                   4620:   /*     y[i][j]=x[i]; */
                   4621:   /*     printf("%.3e ",y[i][j]); */
                   4622:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4623:   /*   } */
                   4624:   /*   printf("\n"); */
                   4625:   /*   fprintf(ficlog,"\n"); */
                   4626:   /* } */
                   4627: 
                   4628:   /* Verifying the inverse matrix */
                   4629: #ifdef DEBUGHESS
                   4630:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4631: 
1.203     brouard  4632:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4633:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4634: 
                   4635:   for (j=1;j<=npar;j++) {
                   4636:     for (i=1;i<=npar;i++){ 
1.203     brouard  4637:       printf("%.2f ",y[i][j]);
                   4638:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4639:     }
                   4640:     printf("\n");
                   4641:     fprintf(ficlog,"\n");
                   4642:   }
1.203     brouard  4643: #endif
1.126     brouard  4644: 
                   4645:   free_matrix(a,1,npar,1,npar);
                   4646:   free_matrix(y,1,npar,1,npar);
                   4647:   free_vector(x,1,npar);
                   4648:   free_ivector(indx,1,npar);
1.203     brouard  4649:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4650: 
                   4651: 
                   4652: }
                   4653: 
                   4654: /*************** hessian matrix ****************/
                   4655: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4656: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4657:   int i;
                   4658:   int l=1, lmax=20;
1.203     brouard  4659:   double k1,k2, res, fx;
1.132     brouard  4660:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4661:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4662:   int k=0,kmax=10;
                   4663:   double l1;
                   4664: 
                   4665:   fx=func(x);
                   4666:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4667:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4668:     l1=pow(10,l);
                   4669:     delts=delt;
                   4670:     for(k=1 ; k <kmax; k=k+1){
                   4671:       delt = delta*(l1*k);
                   4672:       p2[theta]=x[theta] +delt;
1.145     brouard  4673:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4674:       p2[theta]=x[theta]-delt;
                   4675:       k2=func(p2)-fx;
                   4676:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4677:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4678:       
1.203     brouard  4679: #ifdef DEBUGHESSII
1.126     brouard  4680:       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);
                   4681:       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);
                   4682: #endif
                   4683:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4684:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4685:        k=kmax;
                   4686:       }
                   4687:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4688:        k=kmax; l=lmax*10;
1.126     brouard  4689:       }
                   4690:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4691:        delts=delt;
                   4692:       }
1.203     brouard  4693:     } /* End loop k */
1.126     brouard  4694:   }
                   4695:   delti[theta]=delts;
                   4696:   return res; 
                   4697:   
                   4698: }
                   4699: 
1.203     brouard  4700: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4701: {
                   4702:   int i;
1.164     brouard  4703:   int l=1, lmax=20;
1.126     brouard  4704:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4705:   double p2[MAXPARM+1];
1.203     brouard  4706:   int k, kmax=1;
                   4707:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4708: 
                   4709:   int firstime=0;
1.203     brouard  4710:   
1.126     brouard  4711:   fx=func(x);
1.203     brouard  4712:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4713:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4714:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4715:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4716:     k1=func(p2)-fx;
                   4717:   
1.203     brouard  4718:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4719:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4720:     k2=func(p2)-fx;
                   4721:   
1.203     brouard  4722:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4723:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4724:     k3=func(p2)-fx;
                   4725:   
1.203     brouard  4726:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4727:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4728:     k4=func(p2)-fx;
1.203     brouard  4729:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4730:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4731:       firstime=1;
1.203     brouard  4732:       kmax=kmax+10;
1.208     brouard  4733:     }
                   4734:     if(kmax >=10 || firstime ==1){
1.246     brouard  4735:       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);
                   4736:       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  4737:       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);
                   4738:       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);
                   4739:     }
                   4740: #ifdef DEBUGHESSIJ
                   4741:     v1=hess[thetai][thetai];
                   4742:     v2=hess[thetaj][thetaj];
                   4743:     cv12=res;
                   4744:     /* Computing eigen value of Hessian matrix */
                   4745:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4746:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4747:     if ((lc2 <0) || (lc1 <0) ){
                   4748:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4749:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4750:       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);
                   4751:       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);
                   4752:     }
1.126     brouard  4753: #endif
                   4754:   }
                   4755:   return res;
                   4756: }
                   4757: 
1.203     brouard  4758:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4759: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4760: /* { */
                   4761: /*   int i; */
                   4762: /*   int l=1, lmax=20; */
                   4763: /*   double k1,k2,k3,k4,res,fx; */
                   4764: /*   double p2[MAXPARM+1]; */
                   4765: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4766: /*   int k=0,kmax=10; */
                   4767: /*   double l1; */
                   4768:   
                   4769: /*   fx=func(x); */
                   4770: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4771: /*     l1=pow(10,l); */
                   4772: /*     delts=delt; */
                   4773: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4774: /*       delt = delti*(l1*k); */
                   4775: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4776: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4777: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4778: /*       k1=func(p2)-fx; */
                   4779:       
                   4780: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4781: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4782: /*       k2=func(p2)-fx; */
                   4783:       
                   4784: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4785: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4786: /*       k3=func(p2)-fx; */
                   4787:       
                   4788: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4789: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4790: /*       k4=func(p2)-fx; */
                   4791: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4792: /* #ifdef DEBUGHESSIJ */
                   4793: /*       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); */
                   4794: /*       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); */
                   4795: /* #endif */
                   4796: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4797: /*     k=kmax; */
                   4798: /*       } */
                   4799: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4800: /*     k=kmax; l=lmax*10; */
                   4801: /*       } */
                   4802: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4803: /*     delts=delt; */
                   4804: /*       } */
                   4805: /*     } /\* End loop k *\/ */
                   4806: /*   } */
                   4807: /*   delti[theta]=delts; */
                   4808: /*   return res;  */
                   4809: /* } */
                   4810: 
                   4811: 
1.126     brouard  4812: /************** Inverse of matrix **************/
                   4813: void ludcmp(double **a, int n, int *indx, double *d) 
                   4814: { 
                   4815:   int i,imax,j,k; 
                   4816:   double big,dum,sum,temp; 
                   4817:   double *vv; 
                   4818:  
                   4819:   vv=vector(1,n); 
                   4820:   *d=1.0; 
                   4821:   for (i=1;i<=n;i++) { 
                   4822:     big=0.0; 
                   4823:     for (j=1;j<=n;j++) 
                   4824:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4825:     if (big == 0.0){
                   4826:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4827:       for (j=1;j<=n;j++) {
                   4828:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4829:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4830:       }
                   4831:       fflush(ficlog);
                   4832:       fclose(ficlog);
                   4833:       nrerror("Singular matrix in routine ludcmp"); 
                   4834:     }
1.126     brouard  4835:     vv[i]=1.0/big; 
                   4836:   } 
                   4837:   for (j=1;j<=n;j++) { 
                   4838:     for (i=1;i<j;i++) { 
                   4839:       sum=a[i][j]; 
                   4840:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4841:       a[i][j]=sum; 
                   4842:     } 
                   4843:     big=0.0; 
                   4844:     for (i=j;i<=n;i++) { 
                   4845:       sum=a[i][j]; 
                   4846:       for (k=1;k<j;k++) 
                   4847:        sum -= a[i][k]*a[k][j]; 
                   4848:       a[i][j]=sum; 
                   4849:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4850:        big=dum; 
                   4851:        imax=i; 
                   4852:       } 
                   4853:     } 
                   4854:     if (j != imax) { 
                   4855:       for (k=1;k<=n;k++) { 
                   4856:        dum=a[imax][k]; 
                   4857:        a[imax][k]=a[j][k]; 
                   4858:        a[j][k]=dum; 
                   4859:       } 
                   4860:       *d = -(*d); 
                   4861:       vv[imax]=vv[j]; 
                   4862:     } 
                   4863:     indx[j]=imax; 
                   4864:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4865:     if (j != n) { 
                   4866:       dum=1.0/(a[j][j]); 
                   4867:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4868:     } 
                   4869:   } 
                   4870:   free_vector(vv,1,n);  /* Doesn't work */
                   4871: ;
                   4872: } 
                   4873: 
                   4874: void lubksb(double **a, int n, int *indx, double b[]) 
                   4875: { 
                   4876:   int i,ii=0,ip,j; 
                   4877:   double sum; 
                   4878:  
                   4879:   for (i=1;i<=n;i++) { 
                   4880:     ip=indx[i]; 
                   4881:     sum=b[ip]; 
                   4882:     b[ip]=b[i]; 
                   4883:     if (ii) 
                   4884:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4885:     else if (sum) ii=i; 
                   4886:     b[i]=sum; 
                   4887:   } 
                   4888:   for (i=n;i>=1;i--) { 
                   4889:     sum=b[i]; 
                   4890:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4891:     b[i]=sum/a[i][i]; 
                   4892:   } 
                   4893: } 
                   4894: 
                   4895: void pstamp(FILE *fichier)
                   4896: {
1.196     brouard  4897:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4898: }
                   4899: 
1.297     brouard  4900: void date2dmy(double date,double *day, double *month, double *year){
                   4901:   double yp=0., yp1=0., yp2=0.;
                   4902:   
                   4903:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   4904:                        fractional in yp1 */
                   4905:   *year=yp;
                   4906:   yp2=modf((yp1*12),&yp);
                   4907:   *month=yp;
                   4908:   yp1=modf((yp2*30.5),&yp);
                   4909:   *day=yp;
                   4910:   if(*day==0) *day=1;
                   4911:   if(*month==0) *month=1;
                   4912: }
                   4913: 
1.253     brouard  4914: 
                   4915: 
1.126     brouard  4916: /************ Frequencies ********************/
1.251     brouard  4917: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4918:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4919:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4920: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  4921:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  4922:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  4923:   int iind=0, iage=0;
                   4924:   int mi; /* Effective wave */
                   4925:   int first;
                   4926:   double ***freq; /* Frequencies */
1.268     brouard  4927:   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 */
                   4928:   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  4929:   double *meanq, *stdq, *idq;
1.226     brouard  4930:   double **meanqt;
                   4931:   double *pp, **prop, *posprop, *pospropt;
                   4932:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4933:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4934:   double agebegin, ageend;
                   4935:     
                   4936:   pp=vector(1,nlstate);
1.251     brouard  4937:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4938:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4939:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4940:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4941:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  4942:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  4943:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  4944:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4945:   strcpy(fileresp,"P_");
                   4946:   strcat(fileresp,fileresu);
                   4947:   /*strcat(fileresphtm,fileresu);*/
                   4948:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4949:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4950:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4951:     exit(0);
                   4952:   }
1.240     brouard  4953:   
1.226     brouard  4954:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4955:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4956:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4957:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4958:     fflush(ficlog);
                   4959:     exit(70); 
                   4960:   }
                   4961:   else{
                   4962:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4963: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4964: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4965:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4966:   }
1.319     brouard  4967:   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  4968:   
1.226     brouard  4969:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4970:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4971:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4972:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4973:     fflush(ficlog);
                   4974:     exit(70); 
1.240     brouard  4975:   } else{
1.226     brouard  4976:     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  4977: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  4978: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4979:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4980:   }
1.319     brouard  4981:   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  4982:   
1.253     brouard  4983:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4984:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4985:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4986:   j1=0;
1.126     brouard  4987:   
1.227     brouard  4988:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335   ! brouard  4989:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  4990:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  4991:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4992:   
                   4993:   
1.226     brouard  4994:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4995:      reference=low_education V1=0,V2=0
                   4996:      med_educ                V1=1 V2=0, 
                   4997:      high_educ               V1=0 V2=1
1.330     brouard  4998:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  4999:   */
1.249     brouard  5000:   dateintsum=0;
                   5001:   k2cpt=0;
                   5002: 
1.253     brouard  5003:   if(cptcoveff == 0 )
1.265     brouard  5004:     nl=1;  /* Constant and age model only */
1.253     brouard  5005:   else
                   5006:     nl=2;
1.265     brouard  5007: 
                   5008:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5009:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335   ! brouard  5010:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5011:    *     freq[s1][s2][iage] =0.
                   5012:    *     Loop on iind
                   5013:    *       ++freq[s1][s2][iage] weighted
                   5014:    *     end iind
                   5015:    *     if covariate and j!0
                   5016:    *       headers Variable on one line
                   5017:    *     endif cov j!=0
                   5018:    *     header of frequency table by age
                   5019:    *     Loop on age
                   5020:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5021:    *       pos+=freq[s1][s2][iage] weighted
                   5022:    *       Loop on s1 initial state
                   5023:    *         fprintf(ficresp
                   5024:    *       end s1
                   5025:    *     end age
                   5026:    *     if j!=0 computes starting values
                   5027:    *     end compute starting values
                   5028:    *   end j1
                   5029:    * end nl 
                   5030:    */
1.253     brouard  5031:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5032:     if(nj==1)
                   5033:       j=0;  /* First pass for the constant */
1.265     brouard  5034:     else{
1.335   ! brouard  5035:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
1.265     brouard  5036:     }
1.251     brouard  5037:     first=1;
1.332     brouard  5038:     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  5039:       posproptt=0.;
1.330     brouard  5040:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5041:        scanf("%d", i);*/
                   5042:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5043:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5044:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5045:            freq[i][s2][m]=0;
1.251     brouard  5046:       
                   5047:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5048:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5049:          prop[i][m]=0;
                   5050:        posprop[i]=0;
                   5051:        pospropt[i]=0;
                   5052:       }
1.283     brouard  5053:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5054:         idq[z1]=0.;
                   5055:         meanq[z1]=0.;
                   5056:         stdq[z1]=0.;
1.283     brouard  5057:       }
                   5058:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5059:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5060:       /*         meanqt[m][z1]=0.; */
                   5061:       /*       } */
                   5062:       /* }       */
1.251     brouard  5063:       /* dateintsum=0; */
                   5064:       /* k2cpt=0; */
                   5065:       
1.265     brouard  5066:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5067:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5068:        bool=1;
                   5069:        if(j !=0){
                   5070:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335   ! brouard  5071:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          5072:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5073:                /* if(Tvaraff[z1] ==-20){ */
                   5074:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5075:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5076:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5077:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335   ! brouard  5078:                /* if( iind >=imx-3) printf("Searching error iind=%d Tvaraff[z1]=%d covar[Tvaraff[z1]][iind]=%.f TnsdVar[Tvaraff[z1]]=%d, cptcoveff=%d, cptcovs=%d \n",iind, Tvaraff[z1], covar[Tvaraff[z1]][iind],TnsdVar[Tvaraff[z1]],cptcoveff, cptcovs); */
        !          5079:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
        !          5080:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5081:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5082:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5083:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5084:                  /* 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", */
                   5085:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5086:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5087:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5088:                } /* Onlyf fixed */
                   5089:              } /* end z1 */
1.335   ! brouard  5090:            } /* cptcoveff > 0 */
1.251     brouard  5091:          } /* end any */
                   5092:        }/* end j==0 */
1.265     brouard  5093:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5094:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5095:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5096:            m=mw[mi][iind];
                   5097:            if(j!=0){
                   5098:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335   ! brouard  5099:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5100:                  if( Fixed[Tmodelind[z1]]==1){
                   5101:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5102:                    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  5103:                                                                                      value is -1, we don't select. It differs from the 
                   5104:                                                                                      constant and age model which counts them. */
                   5105:                      bool=0; /* not selected */
                   5106:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5107:                    /* i1=Tvaraff[z1]; */
                   5108:                    /* i2=TnsdVar[i1]; */
                   5109:                    /* i3=nbcode[i1][i2]; */
                   5110:                    /* i4=covar[i1][iind]; */
                   5111:                    /* if(i4 != i3){ */
                   5112:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5113:                      bool=0;
                   5114:                    }
                   5115:                  }
                   5116:                }
                   5117:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5118:            } /* end j==0 */
                   5119:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5120:            if(bool==1){ /*Selected */
1.251     brouard  5121:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5122:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5123:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5124:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5125:              if(m >=firstpass && m <=lastpass){
                   5126:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5127:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5128:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5129:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5130:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5131:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5132:                if (m<lastpass) {
                   5133:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5134:                  /*   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]); */
                   5135:                  if(s[m][iind]==-1)
                   5136:                    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.));
                   5137:                  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  5138:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5139:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5140:                      idq[z1]=idq[z1]+weight[iind];
                   5141:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5142:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5143:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5144:                    }
1.284     brouard  5145:                  }
1.251     brouard  5146:                  /* if((int)agev[m][iind] == 55) */
                   5147:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5148:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5149:                  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  5150:                }
1.251     brouard  5151:              } /* end if between passes */  
                   5152:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5153:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5154:                k2cpt++;
                   5155:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5156:              }
1.251     brouard  5157:            }else{
                   5158:              bool=1;
                   5159:            }/* end bool 2 */
                   5160:          } /* end m */
1.284     brouard  5161:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5162:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5163:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5164:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5165:          /* } */
1.251     brouard  5166:        } /* end bool */
                   5167:       } /* end iind = 1 to imx */
1.319     brouard  5168:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5169:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5170:       
                   5171:       
                   5172:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335   ! brouard  5173:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5174:         pstamp(ficresp);
1.335   ! brouard  5175:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5176:         pstamp(ficresp);
1.251     brouard  5177:        printf( "\n#********** Variable "); 
                   5178:        fprintf(ficresp, "\n#********** Variable "); 
                   5179:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5180:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5181:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5182:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5183:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5184:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5185:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5186:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5187:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5188:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5189:          }else{
1.330     brouard  5190:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5191:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5192:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5193:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5194:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5195:          }
                   5196:        }
                   5197:        printf( "**********\n#");
                   5198:        fprintf(ficresp, "**********\n#");
                   5199:        fprintf(ficresphtm, "**********</h3>\n");
                   5200:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5201:        fprintf(ficlog, "**********\n");
                   5202:       }
1.284     brouard  5203:       /*
                   5204:        Printing means of quantitative variables if any
                   5205:       */
                   5206:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5207:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5208:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5209:        if(weightopt==1){
                   5210:          printf(" Weighted mean and standard deviation of");
                   5211:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5212:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5213:        }
1.311     brouard  5214:        /* mu = \frac{w x}{\sum w}
                   5215:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5216:        */
                   5217:        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]));
                   5218:        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]));
                   5219:        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  5220:       }
                   5221:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5222:       /*       for(m=1;m<=lastpass;m++){ */
                   5223:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5224:       /*   } */
                   5225:       /* } */
1.283     brouard  5226: 
1.251     brouard  5227:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335   ! brouard  5228:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5229:         fprintf(ficresp, " Age");
1.335   ! brouard  5230:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
        !          5231:          printf(" V%d=%d, z1=%d, Tvaraff[z1]=%d, j1=%d, TnsdVar[Tvaraff[%d]]=%d |",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])], z1, Tvaraff[z1], j1,z1,TnsdVar[Tvaraff[z1]]);
        !          5232:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
        !          5233:        }
1.251     brouard  5234:       for(i=1; i<=nlstate;i++) {
1.335   ! brouard  5235:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5236:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5237:       }
1.335   ! brouard  5238:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5239:       fprintf(ficresphtm, "\n");
                   5240:       
                   5241:       /* Header of frequency table by age */
                   5242:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5243:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5244:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5245:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5246:          if(s2!=0 && m!=0)
                   5247:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5248:        }
1.226     brouard  5249:       }
1.251     brouard  5250:       fprintf(ficresphtmfr, "\n");
                   5251:     
                   5252:       /* For each age */
                   5253:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5254:        fprintf(ficresphtm,"<tr>");
                   5255:        if(iage==iagemax+1){
                   5256:          fprintf(ficlog,"1");
                   5257:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5258:        }else if(iage==iagemax+2){
                   5259:          fprintf(ficlog,"0");
                   5260:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5261:        }else if(iage==iagemax+3){
                   5262:          fprintf(ficlog,"Total");
                   5263:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5264:        }else{
1.240     brouard  5265:          if(first==1){
1.251     brouard  5266:            first=0;
                   5267:            printf("See log file for details...\n");
                   5268:          }
                   5269:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5270:          fprintf(ficlog,"Age %d", iage);
                   5271:        }
1.265     brouard  5272:        for(s1=1; s1 <=nlstate ; s1++){
                   5273:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5274:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5275:        }
1.265     brouard  5276:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5277:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5278:            pos += freq[s1][m][iage];
                   5279:          if(pp[s1]>=1.e-10){
1.251     brouard  5280:            if(first==1){
1.265     brouard  5281:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5282:            }
1.265     brouard  5283:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5284:          }else{
                   5285:            if(first==1)
1.265     brouard  5286:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5287:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5288:          }
                   5289:        }
                   5290:       
1.265     brouard  5291:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5292:          /* posprop[s1]=0; */
                   5293:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5294:            pp[s1] += freq[s1][m][iage];
                   5295:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5296:       
                   5297:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5298:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5299:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5300:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5301:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5302:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5303:        }
                   5304:        
                   5305:        /* Writing ficresp */
1.335   ! brouard  5306:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5307:           if( iage <= iagemax){
                   5308:            fprintf(ficresp," %d",iage);
                   5309:           }
                   5310:         }else if( nj==2){
                   5311:           if( iage <= iagemax){
                   5312:            fprintf(ficresp," %d",iage);
1.335   ! brouard  5313:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5314:           }
1.240     brouard  5315:        }
1.265     brouard  5316:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5317:          if(pos>=1.e-5){
1.251     brouard  5318:            if(first==1)
1.265     brouard  5319:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5320:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5321:          }else{
                   5322:            if(first==1)
1.265     brouard  5323:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5324:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5325:          }
                   5326:          if( iage <= iagemax){
                   5327:            if(pos>=1.e-5){
1.335   ! brouard  5328:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5329:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5330:               }else if( nj==2){
                   5331:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5332:               }
                   5333:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5334:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5335:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5336:            } else{
1.335   ! brouard  5337:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5338:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5339:            }
1.240     brouard  5340:          }
1.265     brouard  5341:          pospropt[s1] +=posprop[s1];
                   5342:        } /* end loop s1 */
1.251     brouard  5343:        /* pospropt=0.; */
1.265     brouard  5344:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5345:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5346:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5347:              if(first==1){
1.265     brouard  5348:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5349:              }
1.265     brouard  5350:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5351:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5352:            }
1.265     brouard  5353:            if(s1!=0 && m!=0)
                   5354:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5355:          }
1.265     brouard  5356:        } /* end loop s1 */
1.251     brouard  5357:        posproptt=0.; 
1.265     brouard  5358:        for(s1=1; s1 <=nlstate; s1++){
                   5359:          posproptt += pospropt[s1];
1.251     brouard  5360:        }
                   5361:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5362:        fprintf(ficresphtm,"</tr>\n");
1.335   ! brouard  5363:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5364:          if(iage <= iagemax)
                   5365:            fprintf(ficresp,"\n");
1.240     brouard  5366:        }
1.251     brouard  5367:        if(first==1)
                   5368:          printf("Others in log...\n");
                   5369:        fprintf(ficlog,"\n");
                   5370:       } /* end loop age iage */
1.265     brouard  5371:       
1.251     brouard  5372:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5373:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5374:        if(posproptt < 1.e-5){
1.265     brouard  5375:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5376:        }else{
1.265     brouard  5377:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5378:        }
1.226     brouard  5379:       }
1.251     brouard  5380:       fprintf(ficresphtm,"</tr>\n");
                   5381:       fprintf(ficresphtm,"</table>\n");
                   5382:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5383:       if(posproptt < 1.e-5){
1.251     brouard  5384:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5385:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5386:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5387:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5388:        invalidvarcomb[j1]=1;
1.226     brouard  5389:       }else{
1.251     brouard  5390:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   5391:        invalidvarcomb[j1]=0;
1.226     brouard  5392:       }
1.251     brouard  5393:       fprintf(ficresphtmfr,"</table>\n");
                   5394:       fprintf(ficlog,"\n");
                   5395:       if(j!=0){
                   5396:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5397:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5398:          for(k=1; k <=(nlstate+ndeath); k++){
                   5399:            if (k != i) {
1.265     brouard  5400:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5401:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5402:                  if(j1==1){ /* All dummy covariates to zero */
                   5403:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5404:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5405:                    printf("%d%d ",i,k);
                   5406:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5407:                    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]));
                   5408:                    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]));
                   5409:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5410:                  }
1.253     brouard  5411:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5412:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5413:                    x[iage]= (double)iage;
                   5414:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5415:                    /* 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  5416:                  }
1.268     brouard  5417:                  /* Some are not finite, but linreg will ignore these ages */
                   5418:                  no=0;
1.253     brouard  5419:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5420:                  pstart[s1]=b;
                   5421:                  pstart[s1-1]=a;
1.252     brouard  5422:                }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 */ 
                   5423:                  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]);
                   5424:                  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  5425:                  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  5426:                  printf("%d%d ",i,k);
                   5427:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5428:                  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  5429:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5430:                  ;
                   5431:                }
                   5432:                /* printf("%12.7f )", param[i][jj][k]); */
                   5433:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5434:                s1++; 
1.251     brouard  5435:              } /* end jj */
                   5436:            } /* end k!= i */
                   5437:          } /* end k */
1.265     brouard  5438:        } /* end i, s1 */
1.251     brouard  5439:       } /* end j !=0 */
                   5440:     } /* end selected combination of covariate j1 */
                   5441:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5442:       printf("#Freqsummary: Starting values for the constants:\n");
                   5443:       fprintf(ficlog,"\n");
1.265     brouard  5444:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5445:        for(k=1; k <=(nlstate+ndeath); k++){
                   5446:          if (k != i) {
                   5447:            printf("%d%d ",i,k);
                   5448:            fprintf(ficlog,"%d%d ",i,k);
                   5449:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5450:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5451:              if(jj==1){ /* Age has to be done */
1.265     brouard  5452:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5453:                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]));
                   5454:                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  5455:              }
                   5456:              /* printf("%12.7f )", param[i][jj][k]); */
                   5457:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5458:              s1++; 
1.250     brouard  5459:            }
1.251     brouard  5460:            printf("\n");
                   5461:            fprintf(ficlog,"\n");
1.250     brouard  5462:          }
                   5463:        }
1.284     brouard  5464:       } /* end of state i */
1.251     brouard  5465:       printf("#Freqsummary\n");
                   5466:       fprintf(ficlog,"\n");
1.265     brouard  5467:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5468:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5469:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5470:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5471:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5472:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5473:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5474:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5475:          /* } */
                   5476:        }
1.265     brouard  5477:       } /* end loop s1 */
1.251     brouard  5478:       
                   5479:       printf("\n");
                   5480:       fprintf(ficlog,"\n");
                   5481:     } /* end j=0 */
1.249     brouard  5482:   } /* end j */
1.252     brouard  5483: 
1.253     brouard  5484:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5485:     for(i=1, jk=1; i <=nlstate; i++){
                   5486:       for(j=1; j <=nlstate+ndeath; j++){
                   5487:        if(j!=i){
                   5488:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5489:          printf("%1d%1d",i,j);
                   5490:          fprintf(ficparo,"%1d%1d",i,j);
                   5491:          for(k=1; k<=ncovmodel;k++){
                   5492:            /*    printf(" %lf",param[i][j][k]); */
                   5493:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5494:            p[jk]=pstart[jk];
                   5495:            printf(" %f ",pstart[jk]);
                   5496:            fprintf(ficparo," %f ",pstart[jk]);
                   5497:            jk++;
                   5498:          }
                   5499:          printf("\n");
                   5500:          fprintf(ficparo,"\n");
                   5501:        }
                   5502:       }
                   5503:     }
                   5504:   } /* end mle=-2 */
1.226     brouard  5505:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5506:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5507:   
1.226     brouard  5508:   fclose(ficresp);
                   5509:   fclose(ficresphtm);
                   5510:   fclose(ficresphtmfr);
1.283     brouard  5511:   free_vector(idq,1,nqfveff);
1.226     brouard  5512:   free_vector(meanq,1,nqfveff);
1.284     brouard  5513:   free_vector(stdq,1,nqfveff);
1.226     brouard  5514:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5515:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5516:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5517:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5518:   free_vector(pospropt,1,nlstate);
                   5519:   free_vector(posprop,1,nlstate);
1.251     brouard  5520:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5521:   free_vector(pp,1,nlstate);
                   5522:   /* End of freqsummary */
                   5523: }
1.126     brouard  5524: 
1.268     brouard  5525: /* Simple linear regression */
                   5526: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5527: 
                   5528:   /* y=a+bx regression */
                   5529:   double   sumx = 0.0;                        /* sum of x                      */
                   5530:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5531:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5532:   double   sumy = 0.0;                        /* sum of y                      */
                   5533:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5534:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5535:   double yhat;
                   5536:   
                   5537:   double denom=0;
                   5538:   int i;
                   5539:   int ne=*no;
                   5540:   
                   5541:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5542:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5543:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5544:       continue;
                   5545:     }
                   5546:     ne=ne+1;
                   5547:     sumx  += x[i];       
                   5548:     sumx2 += x[i]*x[i];  
                   5549:     sumxy += x[i] * y[i];
                   5550:     sumy  += y[i];      
                   5551:     sumy2 += y[i]*y[i]; 
                   5552:     denom = (ne * sumx2 - sumx*sumx);
                   5553:     /* 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); */
                   5554:   } 
                   5555:   
                   5556:   denom = (ne * sumx2 - sumx*sumx);
                   5557:   if (denom == 0) {
                   5558:     // vertical, slope m is infinity
                   5559:     *b = INFINITY;
                   5560:     *a = 0;
                   5561:     if (r) *r = 0;
                   5562:     return 1;
                   5563:   }
                   5564:   
                   5565:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5566:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5567:   if (r!=NULL) {
                   5568:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5569:       sqrt((sumx2 - sumx*sumx/ne) *
                   5570:           (sumy2 - sumy*sumy/ne));
                   5571:   }
                   5572:   *no=ne;
                   5573:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5574:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5575:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5576:       continue;
                   5577:     }
                   5578:     ne=ne+1;
                   5579:     yhat = y[i] - *a -*b* x[i];
                   5580:     sume2  += yhat * yhat ;       
                   5581:     
                   5582:     denom = (ne * sumx2 - sumx*sumx);
                   5583:     /* 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); */
                   5584:   } 
                   5585:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5586:   *sa= *sb * sqrt(sumx2/ne);
                   5587:   
                   5588:   return 0; 
                   5589: }
                   5590: 
1.126     brouard  5591: /************ Prevalence ********************/
1.227     brouard  5592: 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)
                   5593: {  
                   5594:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5595:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5596:      We still use firstpass and lastpass as another selection.
                   5597:   */
1.126     brouard  5598:  
1.227     brouard  5599:   int i, m, jk, j1, bool, z1,j, iv;
                   5600:   int mi; /* Effective wave */
                   5601:   int iage;
                   5602:   double agebegin, ageend;
                   5603: 
                   5604:   double **prop;
                   5605:   double posprop; 
                   5606:   double  y2; /* in fractional years */
                   5607:   int iagemin, iagemax;
                   5608:   int first; /** to stop verbosity which is redirected to log file */
                   5609: 
                   5610:   iagemin= (int) agemin;
                   5611:   iagemax= (int) agemax;
                   5612:   /*pp=vector(1,nlstate);*/
1.251     brouard  5613:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5614:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5615:   j1=0;
1.222     brouard  5616:   
1.227     brouard  5617:   /*j=cptcoveff;*/
                   5618:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5619:   
1.288     brouard  5620:   first=0;
1.335   ! brouard  5621:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5622:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5623:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5624:        prop[i][iage]=0.0;
                   5625:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5626:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5627:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5628:     
                   5629:     for (i=1; i<=imx; i++) { /* Each individual */
                   5630:       bool=1;
                   5631:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5632:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5633:        m=mw[mi][i];
                   5634:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5635:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5636:        for (z1=1; z1<=cptcoveff; z1++){
                   5637:          if( Fixed[Tmodelind[z1]]==1){
                   5638:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5639:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5640:              bool=0;
                   5641:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5642:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5643:              bool=0;
                   5644:            }
                   5645:        }
                   5646:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5647:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5648:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5649:          if(m >=firstpass && m <=lastpass){
                   5650:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5651:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5652:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5653:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5654:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5655:                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); 
                   5656:                exit(1);
                   5657:              }
                   5658:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5659:                /*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]]);*/
                   5660:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5661:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5662:              } /* end valid statuses */ 
                   5663:            } /* end selection of dates */
                   5664:          } /* end selection of waves */
                   5665:        } /* end bool */
                   5666:       } /* end wave */
                   5667:     } /* end individual */
                   5668:     for(i=iagemin; i <= iagemax+3; i++){  
                   5669:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5670:        posprop += prop[jk][i]; 
                   5671:       } 
                   5672:       
                   5673:       for(jk=1; jk <=nlstate ; jk++){      
                   5674:        if( i <=  iagemax){ 
                   5675:          if(posprop>=1.e-5){ 
                   5676:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5677:          } else{
1.288     brouard  5678:            if(!first){
                   5679:              first=1;
1.266     brouard  5680:              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]);
                   5681:            }else{
1.288     brouard  5682:              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  5683:            }
                   5684:          }
                   5685:        } 
                   5686:       }/* end jk */ 
                   5687:     }/* end i */ 
1.222     brouard  5688:      /*} *//* end i1 */
1.227     brouard  5689:   } /* end j1 */
1.222     brouard  5690:   
1.227     brouard  5691:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5692:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5693:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5694: }  /* End of prevalence */
1.126     brouard  5695: 
                   5696: /************* Waves Concatenation ***************/
                   5697: 
                   5698: 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)
                   5699: {
1.298     brouard  5700:   /* 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  5701:      Death is a valid wave (if date is known).
                   5702:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5703:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5704:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5705:   */
1.126     brouard  5706: 
1.224     brouard  5707:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5708:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5709:      double sum=0., jmean=0.;*/
1.224     brouard  5710:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5711:   int j, k=0,jk, ju, jl;
                   5712:   double sum=0.;
                   5713:   first=0;
1.214     brouard  5714:   firstwo=0;
1.217     brouard  5715:   firsthree=0;
1.218     brouard  5716:   firstfour=0;
1.164     brouard  5717:   jmin=100000;
1.126     brouard  5718:   jmax=-1;
                   5719:   jmean=0.;
1.224     brouard  5720: 
                   5721: /* Treating live states */
1.214     brouard  5722:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5723:     mi=0;  /* First valid wave */
1.227     brouard  5724:     mli=0; /* Last valid wave */
1.309     brouard  5725:     m=firstpass;  /* Loop on waves */
                   5726:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5727:       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 */
                   5728:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5729:       }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  5730:        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  5731:        mli=m;
1.224     brouard  5732:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5733:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5734:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5735:       }
1.309     brouard  5736:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5737: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5738:        break;
1.224     brouard  5739: #else
1.317     brouard  5740:        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  5741:          if(firsthree == 0){
1.302     brouard  5742:            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  5743:            firsthree=1;
1.317     brouard  5744:          }else if(firsthree >=1 && firsthree < 10){
                   5745:            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);
                   5746:            firsthree++;
                   5747:          }else if(firsthree == 10){
                   5748:            printf("Information, too many Information flags: no more reported to log either\n");
                   5749:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5750:            firsthree++;
                   5751:          }else{
                   5752:            firsthree++;
1.227     brouard  5753:          }
1.309     brouard  5754:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5755:          mli=m;
                   5756:        }
                   5757:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5758:          nbwarn++;
1.309     brouard  5759:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5760:            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);
                   5761:            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);
                   5762:          }
                   5763:          break;
                   5764:        }
                   5765:        break;
1.224     brouard  5766: #endif
1.227     brouard  5767:       }/* End m >= lastpass */
1.126     brouard  5768:     }/* end while */
1.224     brouard  5769: 
1.227     brouard  5770:     /* 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  5771:     /* After last pass */
1.224     brouard  5772: /* Treating death states */
1.214     brouard  5773:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5774:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5775:       /* } */
1.126     brouard  5776:       mi++;    /* Death is another wave */
                   5777:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5778:       /* Only death is a correct wave */
1.126     brouard  5779:       mw[mi][i]=m;
1.257     brouard  5780:     } /* else not in a death state */
1.224     brouard  5781: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5782:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5783:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5784:        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  5785:          nbwarn++;
                   5786:          if(firstfiv==0){
1.309     brouard  5787:            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  5788:            firstfiv=1;
                   5789:          }else{
1.309     brouard  5790:            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  5791:          }
1.309     brouard  5792:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5793:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5794:          nberr++;
                   5795:          if(firstwo==0){
1.309     brouard  5796:            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  5797:            firstwo=1;
                   5798:          }
1.309     brouard  5799:          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  5800:        }
1.257     brouard  5801:       }else{ /* if date of interview is unknown */
1.227     brouard  5802:        /* death is known but not confirmed by death status at any wave */
                   5803:        if(firstfour==0){
1.309     brouard  5804:          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  5805:          firstfour=1;
                   5806:        }
1.309     brouard  5807:        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  5808:       }
1.224     brouard  5809:     } /* end if date of death is known */
                   5810: #endif
1.309     brouard  5811:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5812:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5813:     if(mi==0){
                   5814:       nbwarn++;
                   5815:       if(first==0){
1.227     brouard  5816:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5817:        first=1;
1.126     brouard  5818:       }
                   5819:       if(first==1){
1.227     brouard  5820:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5821:       }
                   5822:     } /* end mi==0 */
                   5823:   } /* End individuals */
1.214     brouard  5824:   /* wav and mw are no more changed */
1.223     brouard  5825:        
1.317     brouard  5826:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5827:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5828: 
                   5829: 
1.126     brouard  5830:   for(i=1; i<=imx; i++){
                   5831:     for(mi=1; mi<wav[i];mi++){
                   5832:       if (stepm <=0)
1.227     brouard  5833:        dh[mi][i]=1;
1.126     brouard  5834:       else{
1.260     brouard  5835:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5836:          if (agedc[i] < 2*AGESUP) {
                   5837:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5838:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5839:            else if(j<0){
                   5840:              nberr++;
                   5841:              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]);
                   5842:              j=1; /* Temporary Dangerous patch */
                   5843:              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);
                   5844:              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]);
                   5845:              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);
                   5846:            }
                   5847:            k=k+1;
                   5848:            if (j >= jmax){
                   5849:              jmax=j;
                   5850:              ijmax=i;
                   5851:            }
                   5852:            if (j <= jmin){
                   5853:              jmin=j;
                   5854:              ijmin=i;
                   5855:            }
                   5856:            sum=sum+j;
                   5857:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5858:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5859:          }
                   5860:        }
                   5861:        else{
                   5862:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5863: /*       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  5864:                                        
1.227     brouard  5865:          k=k+1;
                   5866:          if (j >= jmax) {
                   5867:            jmax=j;
                   5868:            ijmax=i;
                   5869:          }
                   5870:          else if (j <= jmin){
                   5871:            jmin=j;
                   5872:            ijmin=i;
                   5873:          }
                   5874:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5875:          /*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]);*/
                   5876:          if(j<0){
                   5877:            nberr++;
                   5878:            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]);
                   5879:            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]);
                   5880:          }
                   5881:          sum=sum+j;
                   5882:        }
                   5883:        jk= j/stepm;
                   5884:        jl= j -jk*stepm;
                   5885:        ju= j -(jk+1)*stepm;
                   5886:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5887:          if(jl==0){
                   5888:            dh[mi][i]=jk;
                   5889:            bh[mi][i]=0;
                   5890:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5891:                  * to avoid the price of an extra matrix product in likelihood */
                   5892:            dh[mi][i]=jk+1;
                   5893:            bh[mi][i]=ju;
                   5894:          }
                   5895:        }else{
                   5896:          if(jl <= -ju){
                   5897:            dh[mi][i]=jk;
                   5898:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5899:                                 * is higher than the multiple of stepm and negative otherwise.
                   5900:                                 */
                   5901:          }
                   5902:          else{
                   5903:            dh[mi][i]=jk+1;
                   5904:            bh[mi][i]=ju;
                   5905:          }
                   5906:          if(dh[mi][i]==0){
                   5907:            dh[mi][i]=1; /* At least one step */
                   5908:            bh[mi][i]=ju; /* At least one step */
                   5909:            /*  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);*/
                   5910:          }
                   5911:        } /* end if mle */
1.126     brouard  5912:       }
                   5913:     } /* end wave */
                   5914:   }
                   5915:   jmean=sum/k;
                   5916:   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  5917:   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  5918: }
1.126     brouard  5919: 
                   5920: /*********** Tricode ****************************/
1.220     brouard  5921:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5922:  {
                   5923:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5924:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5925:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5926:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5927:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5928:     */
1.130     brouard  5929: 
1.242     brouard  5930:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5931:    int modmaxcovj=0; /* Modality max of covariates j */
                   5932:    int cptcode=0; /* Modality max of covariates j */
                   5933:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5934: 
                   5935: 
1.242     brouard  5936:    /* cptcoveff=0;  */
                   5937:    /* *cptcov=0; */
1.126     brouard  5938:  
1.242     brouard  5939:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  5940:    for (k=1; k <= maxncov; k++)
                   5941:      for(j=1; j<=2; j++)
                   5942:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  5943: 
1.242     brouard  5944:    /* Loop on covariates without age and products and no quantitative variable */
1.335   ! brouard  5945:    for (k=1; k<=cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.242     brouard  5946:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5947:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5948:        switch(Fixed[k]) {
                   5949:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  5950:         modmaxcovj=0;
                   5951:         modmincovj=0;
1.242     brouard  5952:         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*/
                   5953:           ij=(int)(covar[Tvar[k]][i]);
                   5954:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5955:            * If product of Vn*Vm, still boolean *:
                   5956:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5957:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5958:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5959:              modality of the nth covariate of individual i. */
                   5960:           if (ij > modmaxcovj)
                   5961:             modmaxcovj=ij; 
                   5962:           else if (ij < modmincovj) 
                   5963:             modmincovj=ij; 
1.287     brouard  5964:           if (ij <0 || ij >1 ){
1.311     brouard  5965:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5966:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   5967:             fflush(ficlog);
                   5968:             exit(1);
1.287     brouard  5969:           }
                   5970:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  5971:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5972:             exit(1);
                   5973:           }else
                   5974:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5975:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5976:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5977:           /* getting the maximum value of the modality of the covariate
                   5978:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5979:              female ies 1, then modmaxcovj=1.
                   5980:           */
                   5981:         } /* end for loop on individuals i */
                   5982:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5983:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5984:         cptcode=modmaxcovj;
                   5985:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5986:         /*for (i=0; i<=cptcode; i++) {*/
                   5987:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5988:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5989:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5990:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5991:             if( j != -1){
                   5992:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5993:                                  covariate for which somebody answered excluding 
                   5994:                                  undefined. Usually 2: 0 and 1. */
                   5995:             }
                   5996:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5997:                                     covariate for which somebody answered including 
                   5998:                                     undefined. Usually 3: -1, 0 and 1. */
                   5999:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6000:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6001:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6002:                        
1.242     brouard  6003:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6004:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6005:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6006:         /* modmincovj=3; modmaxcovj = 7; */
                   6007:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6008:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6009:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6010:         /* nbcode[Tvar[j]][ij]=k; */
                   6011:         /* nbcode[Tvar[j]][1]=0; */
                   6012:         /* nbcode[Tvar[j]][2]=1; */
                   6013:         /* nbcode[Tvar[j]][3]=2; */
                   6014:         /* To be continued (not working yet). */
                   6015:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6016: 
                   6017:         /* 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*/
                   6018:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6019:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6020:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6021:         /*, could be restored in the future */
                   6022:         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  6023:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6024:             break;
                   6025:           }
                   6026:           ij++;
1.287     brouard  6027:           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  6028:           cptcode = ij; /* New max modality for covar j */
                   6029:         } /* end of loop on modality i=-1 to 1 or more */
                   6030:         break;
                   6031:        case 1: /* Testing on varying covariate, could be simple and
                   6032:                * should look at waves or product of fixed *
                   6033:                * varying. No time to test -1, assuming 0 and 1 only */
                   6034:         ij=0;
                   6035:         for(i=0; i<=1;i++){
                   6036:           nbcode[Tvar[k]][++ij]=i;
                   6037:         }
                   6038:         break;
                   6039:        default:
                   6040:         break;
                   6041:        } /* end switch */
                   6042:      } /* end dummy test */
1.334     brouard  6043:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6044:        for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
1.335   ! brouard  6045:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
        !          6046:           printf("Error k=%d \n",k);
        !          6047:           exit(1);
        !          6048:         }
1.311     brouard  6049:         if(isnan(covar[Tvar[k]][i])){
                   6050:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6051:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6052:           fflush(ficlog);
                   6053:           exit(1);
                   6054:          }
                   6055:        }
1.335   ! brouard  6056:      } /* end Quanti */
1.287     brouard  6057:    } /* 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  6058:   
                   6059:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6060:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6061:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6062:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6063:      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 */ 
                   6064:      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 */
                   6065:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6066:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6067:   
                   6068:    ij=0;
                   6069:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
1.335   ! brouard  6070:    for (k=1; k<=  cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
        !          6071:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6072:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6073:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335   ! brouard  6074:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
        !          6075:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
        !          6076:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
1.242     brouard  6077:        /* If product not in single variable we don't print results */
                   6078:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335   ! brouard  6079:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
        !          6080:        /* k=       1    2   3     4       5       6      7       8        9  */
        !          6081:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
        !          6082:        /* ij            1    2                                            3  */  
        !          6083:        /* Tvaraff[ij]=  4    3                                            1  */
        !          6084:        /* Tmodelind[ij]=2    3                                            9  */
        !          6085:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6086:        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*/
                   6087:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6088:        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 */
                   6089:        if(Fixed[k]!=0)
                   6090:         anyvaryingduminmodel=1;
                   6091:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6092:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6093:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6094:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6095:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6096:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6097:      } 
                   6098:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6099:    /* ij--; */
                   6100:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335   ! brouard  6101:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6102:                * because they can be excluded from the model and real
                   6103:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6104:    for(j=ij+1; j<= cptcovt; j++){
                   6105:      Tvaraff[j]=0;
                   6106:      Tmodelind[j]=0;
                   6107:    }
                   6108:    for(j=ntveff+1; j<= cptcovt; j++){
                   6109:      TmodelInvind[j]=0;
                   6110:    }
                   6111:    /* To be sorted */
                   6112:    ;
                   6113:  }
1.126     brouard  6114: 
1.145     brouard  6115: 
1.126     brouard  6116: /*********** Health Expectancies ****************/
                   6117: 
1.235     brouard  6118:  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  6119: 
                   6120: {
                   6121:   /* Health expectancies, no variances */
1.329     brouard  6122:   /* cij is the combination in the list of combination of dummy covariates */
                   6123:   /* strstart is a string of time at start of computing */
1.164     brouard  6124:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6125:   int nhstepma, nstepma; /* Decreasing with age */
                   6126:   double age, agelim, hf;
                   6127:   double ***p3mat;
                   6128:   double eip;
                   6129: 
1.238     brouard  6130:   /* pstamp(ficreseij); */
1.126     brouard  6131:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6132:   fprintf(ficreseij,"# Age");
                   6133:   for(i=1; i<=nlstate;i++){
                   6134:     for(j=1; j<=nlstate;j++){
                   6135:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6136:     }
                   6137:     fprintf(ficreseij," e%1d. ",i);
                   6138:   }
                   6139:   fprintf(ficreseij,"\n");
                   6140: 
                   6141:   
                   6142:   if(estepm < stepm){
                   6143:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6144:   }
                   6145:   else  hstepm=estepm;   
                   6146:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6147:    * This is mainly to measure the difference between two models: for example
                   6148:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6149:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6150:    * progression in between and thus overestimating or underestimating according
                   6151:    * to the curvature of the survival function. If, for the same date, we 
                   6152:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6153:    * to compare the new estimate of Life expectancy with the same linear 
                   6154:    * hypothesis. A more precise result, taking into account a more precise
                   6155:    * curvature will be obtained if estepm is as small as stepm. */
                   6156: 
                   6157:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6158:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6159:      nhstepm is the number of hstepm from age to agelim 
                   6160:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6161:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6162:      and note for a fixed period like estepm months */
                   6163:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6164:      survival function given by stepm (the optimization length). Unfortunately it
                   6165:      means that if the survival funtion is printed only each two years of age and if
                   6166:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6167:      results. So we changed our mind and took the option of the best precision.
                   6168:   */
                   6169:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6170: 
                   6171:   agelim=AGESUP;
                   6172:   /* If stepm=6 months */
                   6173:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6174:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6175:     
                   6176: /* nhstepm age range expressed in number of stepm */
                   6177:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6178:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6179:   /* if (stepm >= YEARM) hstepm=1;*/
                   6180:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6181:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6182: 
                   6183:   for (age=bage; age<=fage; age ++){ 
                   6184:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6185:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6186:     /* if (stepm >= YEARM) hstepm=1;*/
                   6187:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6188: 
                   6189:     /* If stepm=6 months */
                   6190:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6191:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6192:     /* 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  6193:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6194:     
                   6195:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6196:     
                   6197:     printf("%d|",(int)age);fflush(stdout);
                   6198:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6199:     
                   6200:     /* Computing expectancies */
                   6201:     for(i=1; i<=nlstate;i++)
                   6202:       for(j=1; j<=nlstate;j++)
                   6203:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6204:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6205:          
                   6206:          /* 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]);*/
                   6207: 
                   6208:        }
                   6209: 
                   6210:     fprintf(ficreseij,"%3.0f",age );
                   6211:     for(i=1; i<=nlstate;i++){
                   6212:       eip=0;
                   6213:       for(j=1; j<=nlstate;j++){
                   6214:        eip +=eij[i][j][(int)age];
                   6215:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6216:       }
                   6217:       fprintf(ficreseij,"%9.4f", eip );
                   6218:     }
                   6219:     fprintf(ficreseij,"\n");
                   6220:     
                   6221:   }
                   6222:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6223:   printf("\n");
                   6224:   fprintf(ficlog,"\n");
                   6225:   
                   6226: }
                   6227: 
1.235     brouard  6228:  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  6229: 
                   6230: {
                   6231:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6232:      to initial status i, ei. .
1.126     brouard  6233:   */
                   6234:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6235:   int nhstepma, nstepma; /* Decreasing with age */
                   6236:   double age, agelim, hf;
                   6237:   double ***p3matp, ***p3matm, ***varhe;
                   6238:   double **dnewm,**doldm;
                   6239:   double *xp, *xm;
                   6240:   double **gp, **gm;
                   6241:   double ***gradg, ***trgradg;
                   6242:   int theta;
                   6243: 
                   6244:   double eip, vip;
                   6245: 
                   6246:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6247:   xp=vector(1,npar);
                   6248:   xm=vector(1,npar);
                   6249:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6250:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6251:   
                   6252:   pstamp(ficresstdeij);
                   6253:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6254:   fprintf(ficresstdeij,"# Age");
                   6255:   for(i=1; i<=nlstate;i++){
                   6256:     for(j=1; j<=nlstate;j++)
                   6257:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6258:     fprintf(ficresstdeij," e%1d. ",i);
                   6259:   }
                   6260:   fprintf(ficresstdeij,"\n");
                   6261: 
                   6262:   pstamp(ficrescveij);
                   6263:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6264:   fprintf(ficrescveij,"# Age");
                   6265:   for(i=1; i<=nlstate;i++)
                   6266:     for(j=1; j<=nlstate;j++){
                   6267:       cptj= (j-1)*nlstate+i;
                   6268:       for(i2=1; i2<=nlstate;i2++)
                   6269:        for(j2=1; j2<=nlstate;j2++){
                   6270:          cptj2= (j2-1)*nlstate+i2;
                   6271:          if(cptj2 <= cptj)
                   6272:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6273:        }
                   6274:     }
                   6275:   fprintf(ficrescveij,"\n");
                   6276:   
                   6277:   if(estepm < stepm){
                   6278:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6279:   }
                   6280:   else  hstepm=estepm;   
                   6281:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6282:    * This is mainly to measure the difference between two models: for example
                   6283:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6284:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6285:    * progression in between and thus overestimating or underestimating according
                   6286:    * to the curvature of the survival function. If, for the same date, we 
                   6287:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6288:    * to compare the new estimate of Life expectancy with the same linear 
                   6289:    * hypothesis. A more precise result, taking into account a more precise
                   6290:    * curvature will be obtained if estepm is as small as stepm. */
                   6291: 
                   6292:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6293:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6294:      nhstepm is the number of hstepm from age to agelim 
                   6295:      nstepm is the number of stepm from age to agelin. 
                   6296:      Look at hpijx to understand the reason of that which relies in memory size
                   6297:      and note for a fixed period like estepm months */
                   6298:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6299:      survival function given by stepm (the optimization length). Unfortunately it
                   6300:      means that if the survival funtion is printed only each two years of age and if
                   6301:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6302:      results. So we changed our mind and took the option of the best precision.
                   6303:   */
                   6304:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6305: 
                   6306:   /* If stepm=6 months */
                   6307:   /* nhstepm age range expressed in number of stepm */
                   6308:   agelim=AGESUP;
                   6309:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6310:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6311:   /* if (stepm >= YEARM) hstepm=1;*/
                   6312:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6313:   
                   6314:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6315:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6316:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6317:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6318:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6319:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6320: 
                   6321:   for (age=bage; age<=fage; age ++){ 
                   6322:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6323:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6324:     /* if (stepm >= YEARM) hstepm=1;*/
                   6325:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6326:                
1.126     brouard  6327:     /* If stepm=6 months */
                   6328:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6329:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6330:     
                   6331:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6332:                
1.126     brouard  6333:     /* Computing  Variances of health expectancies */
                   6334:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6335:        decrease memory allocation */
                   6336:     for(theta=1; theta <=npar; theta++){
                   6337:       for(i=1; i<=npar; i++){ 
1.222     brouard  6338:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6339:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6340:       }
1.235     brouard  6341:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6342:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6343:                        
1.126     brouard  6344:       for(j=1; j<= nlstate; j++){
1.222     brouard  6345:        for(i=1; i<=nlstate; i++){
                   6346:          for(h=0; h<=nhstepm-1; h++){
                   6347:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6348:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6349:          }
                   6350:        }
1.126     brouard  6351:       }
1.218     brouard  6352:                        
1.126     brouard  6353:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6354:        for(h=0; h<=nhstepm-1; h++){
                   6355:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6356:        }
1.126     brouard  6357:     }/* End theta */
                   6358:     
                   6359:     
                   6360:     for(h=0; h<=nhstepm-1; h++)
                   6361:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6362:        for(theta=1; theta <=npar; theta++)
                   6363:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6364:     
1.218     brouard  6365:                
1.222     brouard  6366:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6367:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6368:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6369:                
1.222     brouard  6370:     printf("%d|",(int)age);fflush(stdout);
                   6371:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6372:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6373:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6374:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6375:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6376:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6377:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6378:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6379:       }
                   6380:     }
1.320     brouard  6381:     /* if((int)age ==50){ */
                   6382:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6383:     /* } */
1.126     brouard  6384:     /* Computing expectancies */
1.235     brouard  6385:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6386:     for(i=1; i<=nlstate;i++)
                   6387:       for(j=1; j<=nlstate;j++)
1.222     brouard  6388:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6389:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6390:                                        
1.222     brouard  6391:          /* 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  6392:                                        
1.222     brouard  6393:        }
1.269     brouard  6394: 
                   6395:     /* Standard deviation of expectancies ij */                
1.126     brouard  6396:     fprintf(ficresstdeij,"%3.0f",age );
                   6397:     for(i=1; i<=nlstate;i++){
                   6398:       eip=0.;
                   6399:       vip=0.;
                   6400:       for(j=1; j<=nlstate;j++){
1.222     brouard  6401:        eip += eij[i][j][(int)age];
                   6402:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6403:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6404:        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  6405:       }
                   6406:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6407:     }
                   6408:     fprintf(ficresstdeij,"\n");
1.218     brouard  6409:                
1.269     brouard  6410:     /* Variance of expectancies ij */          
1.126     brouard  6411:     fprintf(ficrescveij,"%3.0f",age );
                   6412:     for(i=1; i<=nlstate;i++)
                   6413:       for(j=1; j<=nlstate;j++){
1.222     brouard  6414:        cptj= (j-1)*nlstate+i;
                   6415:        for(i2=1; i2<=nlstate;i2++)
                   6416:          for(j2=1; j2<=nlstate;j2++){
                   6417:            cptj2= (j2-1)*nlstate+i2;
                   6418:            if(cptj2 <= cptj)
                   6419:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6420:          }
1.126     brouard  6421:       }
                   6422:     fprintf(ficrescveij,"\n");
1.218     brouard  6423:                
1.126     brouard  6424:   }
                   6425:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6426:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6427:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6428:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6429:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6430:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6431:   printf("\n");
                   6432:   fprintf(ficlog,"\n");
1.218     brouard  6433:        
1.126     brouard  6434:   free_vector(xm,1,npar);
                   6435:   free_vector(xp,1,npar);
                   6436:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6437:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6438:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6439: }
1.218     brouard  6440:  
1.126     brouard  6441: /************ Variance ******************/
1.235     brouard  6442:  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  6443:  {
1.279     brouard  6444:    /** Variance of health expectancies 
                   6445:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6446:     * double **newm;
                   6447:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6448:     */
1.218     brouard  6449:   
                   6450:    /* int movingaverage(); */
                   6451:    double **dnewm,**doldm;
                   6452:    double **dnewmp,**doldmp;
                   6453:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6454:    int first=0;
1.218     brouard  6455:    int k;
                   6456:    double *xp;
1.279     brouard  6457:    double **gp, **gm;  /**< for var eij */
                   6458:    double ***gradg, ***trgradg; /**< for var eij */
                   6459:    double **gradgp, **trgradgp; /**< for var p point j */
                   6460:    double *gpp, *gmp; /**< for var p point j */
                   6461:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6462:    double ***p3mat;
                   6463:    double age,agelim, hf;
                   6464:    /* double ***mobaverage; */
                   6465:    int theta;
                   6466:    char digit[4];
                   6467:    char digitp[25];
                   6468: 
                   6469:    char fileresprobmorprev[FILENAMELENGTH];
                   6470: 
                   6471:    if(popbased==1){
                   6472:      if(mobilav!=0)
                   6473:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6474:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6475:    }
                   6476:    else 
                   6477:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6478: 
1.218     brouard  6479:    /* if (mobilav!=0) { */
                   6480:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6481:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6482:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6483:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6484:    /*   } */
                   6485:    /* } */
                   6486: 
                   6487:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6488:    sprintf(digit,"%-d",ij);
                   6489:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6490:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6491:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6492:    strcat(fileresprobmorprev,fileresu);
                   6493:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6494:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6495:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6496:    }
                   6497:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6498:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6499:    pstamp(ficresprobmorprev);
                   6500:    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  6501:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.334     brouard  6502:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.332     brouard  6503:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  6504:    }
                   6505:    for(j=1;j<=cptcoveff;j++) 
1.334     brouard  6506:      fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]);
1.238     brouard  6507:    fprintf(ficresprobmorprev,"\n");
                   6508: 
1.218     brouard  6509:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6510:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6511:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6512:      for(i=1; i<=nlstate;i++)
                   6513:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6514:    }  
                   6515:    fprintf(ficresprobmorprev,"\n");
                   6516:   
                   6517:    fprintf(ficgp,"\n# Routine varevsij");
                   6518:    fprintf(ficgp,"\nunset title \n");
                   6519:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6520:    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");
                   6521:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6522: 
1.218     brouard  6523:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6524:    pstamp(ficresvij);
                   6525:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6526:    if(popbased==1)
                   6527:      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);
                   6528:    else
                   6529:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6530:    fprintf(ficresvij,"# Age");
                   6531:    for(i=1; i<=nlstate;i++)
                   6532:      for(j=1; j<=nlstate;j++)
                   6533:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6534:    fprintf(ficresvij,"\n");
                   6535: 
                   6536:    xp=vector(1,npar);
                   6537:    dnewm=matrix(1,nlstate,1,npar);
                   6538:    doldm=matrix(1,nlstate,1,nlstate);
                   6539:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6540:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6541: 
                   6542:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6543:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6544:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6545:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6546:   
1.218     brouard  6547:    if(estepm < stepm){
                   6548:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6549:    }
                   6550:    else  hstepm=estepm;   
                   6551:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6552:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6553:       nhstepm is the number of hstepm from age to agelim 
                   6554:       nstepm is the number of stepm from age to agelim. 
                   6555:       Look at function hpijx to understand why because of memory size limitations, 
                   6556:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6557:       survival function given by stepm (the optimization length). Unfortunately it
                   6558:       means that if the survival funtion is printed every two years of age and if
                   6559:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6560:       results. So we changed our mind and took the option of the best precision.
                   6561:    */
                   6562:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6563:    agelim = AGESUP;
                   6564:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6565:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6566:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6567:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6568:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6569:      gp=matrix(0,nhstepm,1,nlstate);
                   6570:      gm=matrix(0,nhstepm,1,nlstate);
                   6571:                
                   6572:                
                   6573:      for(theta=1; theta <=npar; theta++){
                   6574:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6575:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6576:        }
1.279     brouard  6577:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6578:        * returns into prlim .
1.288     brouard  6579:        */
1.242     brouard  6580:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6581: 
                   6582:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6583:        if (popbased==1) {
                   6584:         if(mobilav ==0){
                   6585:           for(i=1; i<=nlstate;i++)
                   6586:             prlim[i][i]=probs[(int)age][i][ij];
                   6587:         }else{ /* mobilav */ 
                   6588:           for(i=1; i<=nlstate;i++)
                   6589:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6590:         }
                   6591:        }
1.295     brouard  6592:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6593:        */                      
                   6594:        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  6595:        /**< 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  6596:        * at horizon h in state j including mortality.
                   6597:        */
1.218     brouard  6598:        for(j=1; j<= nlstate; j++){
                   6599:         for(h=0; h<=nhstepm; h++){
                   6600:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6601:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6602:         }
                   6603:        }
1.279     brouard  6604:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6605:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6606:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6607:        */
                   6608:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6609:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6610:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6611:        }
                   6612:        
                   6613:        /* Again with minus shift */
1.218     brouard  6614:                        
                   6615:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6616:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6617: 
1.242     brouard  6618:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6619:                        
                   6620:        if (popbased==1) {
                   6621:         if(mobilav ==0){
                   6622:           for(i=1; i<=nlstate;i++)
                   6623:             prlim[i][i]=probs[(int)age][i][ij];
                   6624:         }else{ /* mobilav */ 
                   6625:           for(i=1; i<=nlstate;i++)
                   6626:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6627:         }
                   6628:        }
                   6629:                        
1.235     brouard  6630:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6631:                        
                   6632:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6633:         for(h=0; h<=nhstepm; h++){
                   6634:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6635:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6636:         }
                   6637:        }
                   6638:        /* This for computing probability of death (h=1 means
                   6639:          computed over hstepm matrices product = hstepm*stepm months) 
                   6640:          as a weighted average of prlim.
                   6641:        */
                   6642:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6643:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6644:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6645:        }    
1.279     brouard  6646:        /* end shifting computations */
                   6647: 
                   6648:        /**< Computing gradient matrix at horizon h 
                   6649:        */
1.218     brouard  6650:        for(j=1; j<= nlstate; j++) /* vareij */
                   6651:         for(h=0; h<=nhstepm; h++){
                   6652:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6653:         }
1.279     brouard  6654:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6655:        */
                   6656:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6657:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6658:        }
                   6659:                        
                   6660:      } /* End theta */
1.279     brouard  6661:      
                   6662:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6663:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6664:                
                   6665:      for(h=0; h<=nhstepm; h++) /* veij */
                   6666:        for(j=1; j<=nlstate;j++)
                   6667:         for(theta=1; theta <=npar; theta++)
                   6668:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6669:                
                   6670:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6671:        for(theta=1; theta <=npar; theta++)
                   6672:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6673:      /**< as well as its transposed matrix 
                   6674:       */               
1.218     brouard  6675:                
                   6676:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6677:      for(i=1;i<=nlstate;i++)
                   6678:        for(j=1;j<=nlstate;j++)
                   6679:         vareij[i][j][(int)age] =0.;
1.279     brouard  6680: 
                   6681:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6682:       * and k (nhstepm) formula 15 of article
                   6683:       * Lievre-Brouard-Heathcote
                   6684:       */
                   6685:      
1.218     brouard  6686:      for(h=0;h<=nhstepm;h++){
                   6687:        for(k=0;k<=nhstepm;k++){
                   6688:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6689:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6690:         for(i=1;i<=nlstate;i++)
                   6691:           for(j=1;j<=nlstate;j++)
                   6692:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6693:        }
                   6694:      }
                   6695:                
1.279     brouard  6696:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6697:       * p.j overall mortality formula 49 but computed directly because
                   6698:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6699:       * wix is independent of theta.
                   6700:       */
1.218     brouard  6701:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6702:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6703:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6704:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6705:         varppt[j][i]=doldmp[j][i];
                   6706:      /* end ppptj */
                   6707:      /*  x centered again */
                   6708:                
1.242     brouard  6709:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6710:                
                   6711:      if (popbased==1) {
                   6712:        if(mobilav ==0){
                   6713:         for(i=1; i<=nlstate;i++)
                   6714:           prlim[i][i]=probs[(int)age][i][ij];
                   6715:        }else{ /* mobilav */ 
                   6716:         for(i=1; i<=nlstate;i++)
                   6717:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6718:        }
                   6719:      }
                   6720:                
                   6721:      /* This for computing probability of death (h=1 means
                   6722:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6723:        as a weighted average of prlim.
                   6724:      */
1.235     brouard  6725:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6726:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6727:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6728:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6729:      }    
                   6730:      /* end probability of death */
                   6731:                
                   6732:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6733:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6734:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6735:        for(i=1; i<=nlstate;i++){
                   6736:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6737:        }
                   6738:      } 
                   6739:      fprintf(ficresprobmorprev,"\n");
                   6740:                
                   6741:      fprintf(ficresvij,"%.0f ",age );
                   6742:      for(i=1; i<=nlstate;i++)
                   6743:        for(j=1; j<=nlstate;j++){
                   6744:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6745:        }
                   6746:      fprintf(ficresvij,"\n");
                   6747:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6748:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6749:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6750:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6751:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6752:    } /* End age */
                   6753:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6754:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6755:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6756:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6757:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6758:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6759:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6760:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6761:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6762:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6763:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6764:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6765:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6766:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6767:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6768:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6769:    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);
                   6770:    /*  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  6771:     */
1.218     brouard  6772:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6773:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6774: 
1.218     brouard  6775:    free_vector(xp,1,npar);
                   6776:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6777:    free_matrix(dnewm,1,nlstate,1,npar);
                   6778:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6779:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6780:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6781:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6782:    fclose(ficresprobmorprev);
                   6783:    fflush(ficgp);
                   6784:    fflush(fichtm); 
                   6785:  }  /* end varevsij */
1.126     brouard  6786: 
                   6787: /************ Variance of prevlim ******************/
1.269     brouard  6788:  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  6789: {
1.205     brouard  6790:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6791:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6792: 
1.268     brouard  6793:   double **dnewmpar,**doldm;
1.126     brouard  6794:   int i, j, nhstepm, hstepm;
                   6795:   double *xp;
                   6796:   double *gp, *gm;
                   6797:   double **gradg, **trgradg;
1.208     brouard  6798:   double **mgm, **mgp;
1.126     brouard  6799:   double age,agelim;
                   6800:   int theta;
                   6801:   
                   6802:   pstamp(ficresvpl);
1.288     brouard  6803:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6804:   fprintf(ficresvpl,"# Age ");
                   6805:   if(nresult >=1)
                   6806:     fprintf(ficresvpl," Result# ");
1.126     brouard  6807:   for(i=1; i<=nlstate;i++)
                   6808:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6809:   fprintf(ficresvpl,"\n");
                   6810: 
                   6811:   xp=vector(1,npar);
1.268     brouard  6812:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6813:   doldm=matrix(1,nlstate,1,nlstate);
                   6814:   
                   6815:   hstepm=1*YEARM; /* Every year of age */
                   6816:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6817:   agelim = AGESUP;
                   6818:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6819:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6820:     if (stepm >= YEARM) hstepm=1;
                   6821:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6822:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6823:     mgp=matrix(1,npar,1,nlstate);
                   6824:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6825:     gp=vector(1,nlstate);
                   6826:     gm=vector(1,nlstate);
                   6827: 
                   6828:     for(theta=1; theta <=npar; theta++){
                   6829:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6830:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6831:       }
1.288     brouard  6832:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6833:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6834:       /* else */
                   6835:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6836:       for(i=1;i<=nlstate;i++){
1.126     brouard  6837:        gp[i] = prlim[i][i];
1.208     brouard  6838:        mgp[theta][i] = prlim[i][i];
                   6839:       }
1.126     brouard  6840:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6841:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6842:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6843:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6844:       /* else */
                   6845:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6846:       for(i=1;i<=nlstate;i++){
1.126     brouard  6847:        gm[i] = prlim[i][i];
1.208     brouard  6848:        mgm[theta][i] = prlim[i][i];
                   6849:       }
1.126     brouard  6850:       for(i=1;i<=nlstate;i++)
                   6851:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  6852:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  6853:     } /* End theta */
                   6854: 
                   6855:     trgradg =matrix(1,nlstate,1,npar);
                   6856: 
                   6857:     for(j=1; j<=nlstate;j++)
                   6858:       for(theta=1; theta <=npar; theta++)
                   6859:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  6860:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6861:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6862:     /*   for(j=1; j<=nlstate;j++){ */
                   6863:     /*         printf(" %d ",j); */
                   6864:     /*         for(theta=1; theta <=npar; theta++) */
                   6865:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6866:     /*         printf("\n "); */
                   6867:     /*   } */
                   6868:     /* } */
                   6869:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6870:     /*   printf("\n gradg %d ",(int)age); */
                   6871:     /*   for(j=1; j<=nlstate;j++){ */
                   6872:     /*         printf("%d ",j); */
                   6873:     /*         for(theta=1; theta <=npar; theta++) */
                   6874:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6875:     /*         printf("\n "); */
                   6876:     /*   } */
                   6877:     /* } */
1.126     brouard  6878: 
                   6879:     for(i=1;i<=nlstate;i++)
                   6880:       varpl[i][(int)age] =0.;
1.209     brouard  6881:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  6882:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6883:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6884:     }else{
1.268     brouard  6885:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6886:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6887:     }
1.126     brouard  6888:     for(i=1;i<=nlstate;i++)
                   6889:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6890: 
                   6891:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6892:     if(nresult >=1)
                   6893:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  6894:     for(i=1; i<=nlstate;i++){
1.126     brouard  6895:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  6896:       /* for(j=1;j<=nlstate;j++) */
                   6897:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   6898:     }
1.126     brouard  6899:     fprintf(ficresvpl,"\n");
                   6900:     free_vector(gp,1,nlstate);
                   6901:     free_vector(gm,1,nlstate);
1.208     brouard  6902:     free_matrix(mgm,1,npar,1,nlstate);
                   6903:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6904:     free_matrix(gradg,1,npar,1,nlstate);
                   6905:     free_matrix(trgradg,1,nlstate,1,npar);
                   6906:   } /* End age */
                   6907: 
                   6908:   free_vector(xp,1,npar);
                   6909:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  6910:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   6911: 
                   6912: }
                   6913: 
                   6914: 
                   6915: /************ Variance of backprevalence limit ******************/
1.269     brouard  6916:  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  6917: {
                   6918:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   6919:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   6920: 
                   6921:   double **dnewmpar,**doldm;
                   6922:   int i, j, nhstepm, hstepm;
                   6923:   double *xp;
                   6924:   double *gp, *gm;
                   6925:   double **gradg, **trgradg;
                   6926:   double **mgm, **mgp;
                   6927:   double age,agelim;
                   6928:   int theta;
                   6929:   
                   6930:   pstamp(ficresvbl);
                   6931:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   6932:   fprintf(ficresvbl,"# Age ");
                   6933:   if(nresult >=1)
                   6934:     fprintf(ficresvbl," Result# ");
                   6935:   for(i=1; i<=nlstate;i++)
                   6936:       fprintf(ficresvbl," %1d-%1d",i,i);
                   6937:   fprintf(ficresvbl,"\n");
                   6938: 
                   6939:   xp=vector(1,npar);
                   6940:   dnewmpar=matrix(1,nlstate,1,npar);
                   6941:   doldm=matrix(1,nlstate,1,nlstate);
                   6942:   
                   6943:   hstepm=1*YEARM; /* Every year of age */
                   6944:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6945:   agelim = AGEINF;
                   6946:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   6947:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6948:     if (stepm >= YEARM) hstepm=1;
                   6949:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6950:     gradg=matrix(1,npar,1,nlstate);
                   6951:     mgp=matrix(1,npar,1,nlstate);
                   6952:     mgm=matrix(1,npar,1,nlstate);
                   6953:     gp=vector(1,nlstate);
                   6954:     gm=vector(1,nlstate);
                   6955: 
                   6956:     for(theta=1; theta <=npar; theta++){
                   6957:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6958:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6959:       }
                   6960:       if(mobilavproj > 0 )
                   6961:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6962:       else
                   6963:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6964:       for(i=1;i<=nlstate;i++){
                   6965:        gp[i] = bprlim[i][i];
                   6966:        mgp[theta][i] = bprlim[i][i];
                   6967:       }
                   6968:      for(i=1; i<=npar; i++) /* Computes gradient */
                   6969:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   6970:        if(mobilavproj > 0 )
                   6971:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6972:        else
                   6973:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   6974:       for(i=1;i<=nlstate;i++){
                   6975:        gm[i] = bprlim[i][i];
                   6976:        mgm[theta][i] = bprlim[i][i];
                   6977:       }
                   6978:       for(i=1;i<=nlstate;i++)
                   6979:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   6980:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   6981:     } /* End theta */
                   6982: 
                   6983:     trgradg =matrix(1,nlstate,1,npar);
                   6984: 
                   6985:     for(j=1; j<=nlstate;j++)
                   6986:       for(theta=1; theta <=npar; theta++)
                   6987:        trgradg[j][theta]=gradg[theta][j];
                   6988:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6989:     /*   printf("\nmgm mgp %d ",(int)age); */
                   6990:     /*   for(j=1; j<=nlstate;j++){ */
                   6991:     /*         printf(" %d ",j); */
                   6992:     /*         for(theta=1; theta <=npar; theta++) */
                   6993:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6994:     /*         printf("\n "); */
                   6995:     /*   } */
                   6996:     /* } */
                   6997:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6998:     /*   printf("\n gradg %d ",(int)age); */
                   6999:     /*   for(j=1; j<=nlstate;j++){ */
                   7000:     /*         printf("%d ",j); */
                   7001:     /*         for(theta=1; theta <=npar; theta++) */
                   7002:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7003:     /*         printf("\n "); */
                   7004:     /*   } */
                   7005:     /* } */
                   7006: 
                   7007:     for(i=1;i<=nlstate;i++)
                   7008:       varbpl[i][(int)age] =0.;
                   7009:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7010:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7011:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7012:     }else{
                   7013:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7014:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7015:     }
                   7016:     for(i=1;i<=nlstate;i++)
                   7017:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7018: 
                   7019:     fprintf(ficresvbl,"%.0f ",age );
                   7020:     if(nresult >=1)
                   7021:       fprintf(ficresvbl,"%d ",nres );
                   7022:     for(i=1; i<=nlstate;i++)
                   7023:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7024:     fprintf(ficresvbl,"\n");
                   7025:     free_vector(gp,1,nlstate);
                   7026:     free_vector(gm,1,nlstate);
                   7027:     free_matrix(mgm,1,npar,1,nlstate);
                   7028:     free_matrix(mgp,1,npar,1,nlstate);
                   7029:     free_matrix(gradg,1,npar,1,nlstate);
                   7030:     free_matrix(trgradg,1,nlstate,1,npar);
                   7031:   } /* End age */
                   7032: 
                   7033:   free_vector(xp,1,npar);
                   7034:   free_matrix(doldm,1,nlstate,1,npar);
                   7035:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7036: 
                   7037: }
                   7038: 
                   7039: /************ Variance of one-step probabilities  ******************/
                   7040: 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  7041:  {
                   7042:    int i, j=0,  k1, l1, tj;
                   7043:    int k2, l2, j1,  z1;
                   7044:    int k=0, l;
                   7045:    int first=1, first1, first2;
1.326     brouard  7046:    int nres=0; /* New */
1.222     brouard  7047:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7048:    double **dnewm,**doldm;
                   7049:    double *xp;
                   7050:    double *gp, *gm;
                   7051:    double **gradg, **trgradg;
                   7052:    double **mu;
                   7053:    double age, cov[NCOVMAX+1];
                   7054:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7055:    int theta;
                   7056:    char fileresprob[FILENAMELENGTH];
                   7057:    char fileresprobcov[FILENAMELENGTH];
                   7058:    char fileresprobcor[FILENAMELENGTH];
                   7059:    double ***varpij;
                   7060: 
                   7061:    strcpy(fileresprob,"PROB_"); 
                   7062:    strcat(fileresprob,fileres);
                   7063:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7064:      printf("Problem with resultfile: %s\n", fileresprob);
                   7065:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7066:    }
                   7067:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7068:    strcat(fileresprobcov,fileresu);
                   7069:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7070:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7071:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7072:    }
                   7073:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7074:    strcat(fileresprobcor,fileresu);
                   7075:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7076:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7077:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7078:    }
                   7079:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7080:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7081:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7082:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7083:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7084:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7085:    pstamp(ficresprob);
                   7086:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7087:    fprintf(ficresprob,"# Age");
                   7088:    pstamp(ficresprobcov);
                   7089:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7090:    fprintf(ficresprobcov,"# Age");
                   7091:    pstamp(ficresprobcor);
                   7092:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7093:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7094: 
                   7095: 
1.222     brouard  7096:    for(i=1; i<=nlstate;i++)
                   7097:      for(j=1; j<=(nlstate+ndeath);j++){
                   7098:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7099:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7100:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7101:      }  
                   7102:    /* fprintf(ficresprob,"\n");
                   7103:       fprintf(ficresprobcov,"\n");
                   7104:       fprintf(ficresprobcor,"\n");
                   7105:    */
                   7106:    xp=vector(1,npar);
                   7107:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7108:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7109:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7110:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7111:    first=1;
                   7112:    fprintf(ficgp,"\n# Routine varprob");
                   7113:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7114:    fprintf(fichtm,"\n");
                   7115: 
1.288     brouard  7116:    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  7117:    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);
                   7118:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7119: and drawn. It helps understanding how is the covariance between two incidences.\
                   7120:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7121:    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  7122: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7123: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7124: standard deviations wide on each axis. <br>\
                   7125:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7126:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7127: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7128: 
1.222     brouard  7129:    cov[1]=1;
                   7130:    /* tj=cptcoveff; */
1.225     brouard  7131:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7132:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7133:    j1=0;
1.332     brouard  7134: 
                   7135:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7136:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7137:      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  7138:      if(tj != 1 && TKresult[nres]!= j1)
                   7139:        continue;
                   7140: 
                   7141:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7142:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7143:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7144:      if  (cptcovn>0) {
1.334     brouard  7145:        fprintf(ficresprob, "\n#********** Variable ");
                   7146:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7147:        fprintf(ficgp, "\n#********** Variable ");
                   7148:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7149:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7150: 
                   7151:        /* Including quantitative variables of the resultline to be done */
                   7152:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
                   7153:         printf("Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7154:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s \n",nres, z1, modelresult[nres][z1], model);
                   7155:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
                   7156:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7157:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7158:             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  */
                   7159:             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  */
                   7160:             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  */
                   7161:             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  */
                   7162:             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  */
                   7163:             fprintf(ficresprob,"fixed ");
                   7164:             fprintf(ficresprobcov,"fixed ");
                   7165:             fprintf(ficgp,"fixed ");
                   7166:             fprintf(fichtmcov,"fixed ");
                   7167:             fprintf(ficresprobcor,"fixed ");
                   7168:           }else{
                   7169:             fprintf(ficresprob,"varyi ");
                   7170:             fprintf(ficresprobcov,"varyi ");
                   7171:             fprintf(ficgp,"varyi ");
                   7172:             fprintf(fichtmcov,"varyi ");
                   7173:             fprintf(ficresprobcor,"varyi ");
                   7174:           }
                   7175:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7176:           /* For each selected (single) quantitative value */
                   7177:           fprintf(ficresprob," V%d=%f ",Tvqresult[nres][z1],Tqresult[nres][z1]);
                   7178:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7179:             fprintf(ficresprob,"fixed ");
                   7180:             fprintf(ficresprobcov,"fixed ");
                   7181:             fprintf(ficgp,"fixed ");
                   7182:             fprintf(fichtmcov,"fixed ");
                   7183:             fprintf(ficresprobcor,"fixed ");
                   7184:           }else{
                   7185:             fprintf(ficresprob,"varyi ");
                   7186:             fprintf(ficresprobcov,"varyi ");
                   7187:             fprintf(ficgp,"varyi ");
                   7188:             fprintf(fichtmcov,"varyi ");
                   7189:             fprintf(ficresprobcor,"varyi ");
                   7190:           }
                   7191:         }else{
                   7192:           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 */
                   7193:           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 */
                   7194:           exit(1);
                   7195:         }
                   7196:        } /* End loop on variable of this resultline */
                   7197:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7198:        fprintf(ficresprob, "**********\n#\n");
                   7199:        fprintf(ficresprobcov, "**********\n#\n");
                   7200:        fprintf(ficgp, "**********\n#\n");
                   7201:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7202:        fprintf(ficresprobcor, "**********\n#");    
                   7203:        if(invalidvarcomb[j1]){
                   7204:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7205:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7206:         continue;
                   7207:        }
                   7208:      }
                   7209:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7210:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7211:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7212:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7213:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7214:        cov[2]=age;
                   7215:        if(nagesqr==1)
                   7216:         cov[3]= age*age;
1.334     brouard  7217:        /* New code end of combination but for each resultline */
                   7218:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7219:         if(Typevar[k1]==1){ /* A product with age */
                   7220:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7221:         }else{
1.334     brouard  7222:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7223:         }
1.334     brouard  7224:        }/* End of loop on model equation */
                   7225: /* Old code */
                   7226:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7227:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7228:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7229:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7230:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7231:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7232:        /*                                                                  * 1  1 1 1 1 */
                   7233:        /*                                                                  * 2  2 1 1 1 */
                   7234:        /*                                                                  * 3  1 2 1 1 */
                   7235:        /*                                                                  *\/ */
                   7236:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7237:        /* } */
                   7238:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7239:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7240:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7241:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7242:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7243:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7244:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7245:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7246:        /*         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]); */
                   7247:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7248:        /*         /\* exit(1); *\/ */
                   7249:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7250:        /*       } */
                   7251:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7252:        /* } */
                   7253:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7254:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7255:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7256:        /*           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]])]; */
                   7257:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7258:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7259:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7260:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7261:        /*         } */
                   7262:        /*       }else{ */
                   7263:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7264:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7265:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7266:        /*         }else{ */
                   7267:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7268:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7269:        /*         } */
                   7270:        /*       } */
                   7271:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7272:        /* } */                 
1.326     brouard  7273: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7274:        for(theta=1; theta <=npar; theta++){
                   7275:         for(i=1; i<=npar; i++)
                   7276:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7277:                                
1.222     brouard  7278:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7279:                                
1.222     brouard  7280:         k=0;
                   7281:         for(i=1; i<= (nlstate); i++){
                   7282:           for(j=1; j<=(nlstate+ndeath);j++){
                   7283:             k=k+1;
                   7284:             gp[k]=pmmij[i][j];
                   7285:           }
                   7286:         }
1.220     brouard  7287:                                
1.222     brouard  7288:         for(i=1; i<=npar; i++)
                   7289:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7290:                                
1.222     brouard  7291:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7292:         k=0;
                   7293:         for(i=1; i<=(nlstate); i++){
                   7294:           for(j=1; j<=(nlstate+ndeath);j++){
                   7295:             k=k+1;
                   7296:             gm[k]=pmmij[i][j];
                   7297:           }
                   7298:         }
1.220     brouard  7299:                                
1.222     brouard  7300:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7301:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7302:        }
1.126     brouard  7303: 
1.222     brouard  7304:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7305:         for(theta=1; theta <=npar; theta++)
                   7306:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7307:                        
1.222     brouard  7308:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7309:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7310:                        
1.222     brouard  7311:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7312:                        
1.222     brouard  7313:        k=0;
                   7314:        for(i=1; i<=(nlstate); i++){
                   7315:         for(j=1; j<=(nlstate+ndeath);j++){
                   7316:           k=k+1;
                   7317:           mu[k][(int) age]=pmmij[i][j];
                   7318:         }
                   7319:        }
                   7320:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7321:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7322:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7323:                        
1.222     brouard  7324:        /*printf("\n%d ",(int)age);
                   7325:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7326:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7327:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7328:         }*/
1.220     brouard  7329:                        
1.222     brouard  7330:        fprintf(ficresprob,"\n%d ",(int)age);
                   7331:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7332:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7333:                        
1.222     brouard  7334:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7335:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7336:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7337:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7338:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7339:        }
                   7340:        i=0;
                   7341:        for (k=1; k<=(nlstate);k++){
                   7342:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7343:           i++;
                   7344:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7345:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7346:           for (j=1; j<=i;j++){
                   7347:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7348:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7349:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7350:           }
                   7351:         }
                   7352:        }/* end of loop for state */
                   7353:      } /* end of loop for age */
                   7354:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7355:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7356:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7357:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7358:     
                   7359:      /* Confidence intervalle of pij  */
                   7360:      /*
                   7361:        fprintf(ficgp,"\nunset parametric;unset label");
                   7362:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7363:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7364:        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);
                   7365:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7366:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7367:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7368:      */
                   7369:                
                   7370:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7371:      first1=1;first2=2;
                   7372:      for (k2=1; k2<=(nlstate);k2++){
                   7373:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7374:         if(l2==k2) continue;
                   7375:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7376:         for (k1=1; k1<=(nlstate);k1++){
                   7377:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7378:             if(l1==k1) continue;
                   7379:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7380:             if(i<=j) continue;
                   7381:             for (age=bage; age<=fage; age ++){ 
                   7382:               if ((int)age %5==0){
                   7383:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7384:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7385:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7386:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7387:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7388:                 c12=cv12/sqrt(v1*v2);
                   7389:                 /* Computing eigen value of matrix of covariance */
                   7390:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7391:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7392:                 if ((lc2 <0) || (lc1 <0) ){
                   7393:                   if(first2==1){
                   7394:                     first1=0;
                   7395:                     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);
                   7396:                   }
                   7397:                   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);
                   7398:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7399:                   /* lc2=fabs(lc2); */
                   7400:                 }
1.220     brouard  7401:                                                                
1.222     brouard  7402:                 /* Eigen vectors */
1.280     brouard  7403:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7404:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7405:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7406:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7407:                 }else
                   7408:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7409:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7410:                 v21=(lc1-v1)/cv12*v11;
                   7411:                 v12=-v21;
                   7412:                 v22=v11;
                   7413:                 tnalp=v21/v11;
                   7414:                 if(first1==1){
                   7415:                   first1=0;
                   7416:                   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);
                   7417:                 }
                   7418:                 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);
                   7419:                 /*printf(fignu*/
                   7420:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7421:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7422:                 if(first==1){
                   7423:                   first=0;
                   7424:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7425:                   fprintf(ficgp,"\nset parametric;unset label");
                   7426:                   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);
                   7427:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7428:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7429:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7430: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7431:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7432:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7433:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7434:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7435:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7436:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7437:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7438:                   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  7439:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7440:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7441:                 }else{
                   7442:                   first=0;
                   7443:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7444:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7445:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7446:                   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  7447:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7448:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7449:                 }/* if first */
                   7450:               } /* age mod 5 */
                   7451:             } /* end loop age */
                   7452:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7453:             first=1;
                   7454:           } /*l12 */
                   7455:         } /* k12 */
                   7456:        } /*l1 */
                   7457:      }/* k1 */
1.332     brouard  7458:    }  /* loop on combination of covariates j1 */
1.326     brouard  7459:    } /* loop on nres */
1.222     brouard  7460:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7461:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7462:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7463:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7464:    free_vector(xp,1,npar);
                   7465:    fclose(ficresprob);
                   7466:    fclose(ficresprobcov);
                   7467:    fclose(ficresprobcor);
                   7468:    fflush(ficgp);
                   7469:    fflush(fichtmcov);
                   7470:  }
1.126     brouard  7471: 
                   7472: 
                   7473: /******************* Printing html file ***********/
1.201     brouard  7474: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7475:                  int lastpass, int stepm, int weightopt, char model[],\
                   7476:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7477:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7478:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7479:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7480:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7481:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7482:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7483:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7484: </ul>");
1.319     brouard  7485: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7486: /* </ul>", model); */
1.214     brouard  7487:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7488:    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",
                   7489:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7490:    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  7491:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7492:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7493:    fprintf(fichtm,"\
                   7494:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7495:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7496:    fprintf(fichtm,"\
1.217     brouard  7497:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7498:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7499:    fprintf(fichtm,"\
1.288     brouard  7500:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7501:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7502:    fprintf(fichtm,"\
1.288     brouard  7503:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7504:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7505:    fprintf(fichtm,"\
1.211     brouard  7506:  - (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  7507:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7508:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7509:    if(prevfcast==1){
                   7510:      fprintf(fichtm,"\
                   7511:  - Prevalence projections by age and states:                           \
1.201     brouard  7512:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7513:    }
1.126     brouard  7514: 
                   7515: 
1.225     brouard  7516:    m=pow(2,cptcoveff);
1.222     brouard  7517:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7518: 
1.317     brouard  7519:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7520: 
                   7521:    jj1=0;
                   7522: 
                   7523:    fprintf(fichtm," \n<ul>");
                   7524:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7525:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7526:      if(m != 1 && TKresult[nres]!= k1)
                   7527:        continue;
                   7528:      jj1++;
                   7529:      if (cptcovn > 0) {
                   7530:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   7531:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7532:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7533:        }
                   7534:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7535:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7536:        }
                   7537:        fprintf(fichtm,"\">");
                   7538:        
                   7539:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7540:        fprintf(fichtm,"************ Results for covariates");
                   7541:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7542:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7543:        }
                   7544:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7545:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7546:        }
                   7547:        if(invalidvarcomb[k1]){
                   7548:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7549:         continue;
                   7550:        }
                   7551:        fprintf(fichtm,"</a></li>");
                   7552:      } /* cptcovn >0 */
                   7553:    }
1.317     brouard  7554:    fprintf(fichtm," \n</ul>");
1.264     brouard  7555: 
1.222     brouard  7556:    jj1=0;
1.237     brouard  7557: 
                   7558:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  7559:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  7560:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7561:        continue;
1.220     brouard  7562: 
1.222     brouard  7563:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7564:      jj1++;
                   7565:      if (cptcovn > 0) {
1.264     brouard  7566:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   7567:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7568:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7569:        }
                   7570:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7571:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7572:        }
                   7573:        fprintf(fichtm,"\"</a>");
                   7574:  
1.222     brouard  7575:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  7576:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  7577:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7578:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   7579:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7580:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7581:        }
1.237     brouard  7582:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7583:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7584:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   7585:       }
                   7586:        
1.230     brouard  7587:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.321     brouard  7588:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7589:        if(invalidvarcomb[k1]){
                   7590:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7591:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7592:         continue;
                   7593:        }
                   7594:      }
                   7595:      /* aij, bij */
1.259     brouard  7596:      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  7597: <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  7598:      /* Pij */
1.241     brouard  7599:      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> \
                   7600: <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  7601:      /* Quasi-incidences */
                   7602:      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  7603:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7604:  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  7605: 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> \
                   7606: <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  7607:      /* Survival functions (period) in state j */
                   7608:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7609:        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);
                   7610:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7611:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7612:      }
                   7613:      /* State specific survival functions (period) */
                   7614:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7615:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7616:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7617:  <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);
                   7618:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7619:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7620:      }
1.288     brouard  7621:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7622:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7623:        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);
                   7624:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"P_"),subdirf2(optionfilefiname,"P_"));
                   7625:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7626:      }
1.296     brouard  7627:      if(prevbcast==1){
1.288     brouard  7628:        /* Backward prevalence in each health state */
1.222     brouard  7629:        for(cpt=1; cpt<=nlstate;cpt++){
1.264     brouard  7630:         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  7631: <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  7632:        }
1.217     brouard  7633:      }
1.222     brouard  7634:      if(prevfcast==1){
1.288     brouard  7635:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7636:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7637:         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);
                   7638:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7639:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7640:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7641:        }
                   7642:      }
1.296     brouard  7643:      if(prevbcast==1){
1.268     brouard  7644:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7645:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7646:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7647:  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 \
                   7648:  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  7649: 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);
                   7650:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7651:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7652:        }
                   7653:      }
1.220     brouard  7654:         
1.222     brouard  7655:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7656:        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);
                   7657:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7658:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7659:      }
                   7660:      /* } /\* end i1 *\/ */
                   7661:    }/* End k1 */
                   7662:    fprintf(fichtm,"</ul>");
1.126     brouard  7663: 
1.222     brouard  7664:    fprintf(fichtm,"\
1.126     brouard  7665: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7666:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7667:  - 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  7668: But because parameters are usually highly correlated (a higher incidence of disability \
                   7669: and a higher incidence of recovery can give very close observed transition) it might \
                   7670: be very useful to look not only at linear confidence intervals estimated from the \
                   7671: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7672: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7673: covariance matrix of the one-step probabilities. \
                   7674: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7675: 
1.222     brouard  7676:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7677:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7678:    fprintf(fichtm,"\
1.126     brouard  7679:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7680:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7681: 
1.222     brouard  7682:    fprintf(fichtm,"\
1.126     brouard  7683:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7684:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7685:    fprintf(fichtm,"\
1.126     brouard  7686:  - 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): \
                   7687:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7688:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7689:    fprintf(fichtm,"\
1.126     brouard  7690:  - (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): \
                   7691:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7692:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7693:    fprintf(fichtm,"\
1.288     brouard  7694:  - 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  7695:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7696:    fprintf(fichtm,"\
1.128     brouard  7697:  - 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  7698:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7699:    fprintf(fichtm,"\
1.288     brouard  7700:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7701:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7702: 
                   7703: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7704: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7705: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7706: /*     <br>",fileres,fileres,fileres,fileres); */
                   7707: /*  else  */
                   7708: /*    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  7709:    fflush(fichtm);
1.126     brouard  7710: 
1.225     brouard  7711:    m=pow(2,cptcoveff);
1.222     brouard  7712:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7713: 
1.317     brouard  7714:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7715: 
                   7716:   jj1=0;
                   7717: 
                   7718:    fprintf(fichtm," \n<ul>");
                   7719:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7720:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
                   7721:      if(m != 1 && TKresult[nres]!= k1)
                   7722:        continue;
                   7723:      jj1++;
                   7724:      if (cptcovn > 0) {
                   7725:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   7726:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7727:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7728:        }
                   7729:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7730:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7731:        }
                   7732:        fprintf(fichtm,"\">");
                   7733:        
                   7734:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7735:        fprintf(fichtm,"************ Results for covariates");
                   7736:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7737:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7738:        }
                   7739:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7740:         fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7741:        }
                   7742:        if(invalidvarcomb[k1]){
                   7743:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7744:         continue;
                   7745:        }
                   7746:        fprintf(fichtm,"</a></li>");
                   7747:      } /* cptcovn >0 */
                   7748:    }
                   7749:    fprintf(fichtm," \n</ul>");
                   7750: 
1.222     brouard  7751:    jj1=0;
1.237     brouard  7752: 
1.241     brouard  7753:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  7754:    for(k1=1; k1<=m;k1++){
1.253     brouard  7755:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7756:        continue;
1.222     brouard  7757:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7758:      jj1++;
1.126     brouard  7759:      if (cptcovn > 0) {
1.317     brouard  7760:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   7761:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   7762:         fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   7763:        }
                   7764:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7765:         fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7766:        }
                   7767:        fprintf(fichtm,"\"</a>");
                   7768:        
1.126     brouard  7769:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.317     brouard  7770:        for (cpt=1; cpt<=cptcoveff;cpt++){  /**< cptcoveff number of variables */
1.237     brouard  7771:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
1.317     brouard  7772:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
1.237     brouard  7773:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7774:        }
1.237     brouard  7775:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7776:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7777:       }
                   7778: 
1.321     brouard  7779:        fprintf(fichtm," (model=%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7780: 
1.222     brouard  7781:        if(invalidvarcomb[k1]){
                   7782:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7783:         continue;
                   7784:        }
1.126     brouard  7785:      }
                   7786:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7787:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7788: 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);
                   7789:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7790:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7791:      }
                   7792:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7793: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7794: true period expectancies (those weighted with period prevalences are also\
                   7795:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7796:  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);
                   7797:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7798:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7799:      /* } /\* end i1 *\/ */
                   7800:    }/* End k1 */
1.241     brouard  7801:   }/* End nres */
1.222     brouard  7802:    fprintf(fichtm,"</ul>");
                   7803:    fflush(fichtm);
1.126     brouard  7804: }
                   7805: 
                   7806: /******************* Gnuplot file **************/
1.296     brouard  7807: 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  7808: 
                   7809:   char dirfileres[132],optfileres[132];
1.264     brouard  7810:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7811:   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  7812:   int lv=0, vlv=0, kl=0;
1.130     brouard  7813:   int ng=0;
1.201     brouard  7814:   int vpopbased;
1.223     brouard  7815:   int ioffset; /* variable offset for columns */
1.270     brouard  7816:   int iyearc=1; /* variable column for year of projection  */
                   7817:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7818:   int nres=0; /* Index of resultline */
1.266     brouard  7819:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7820: 
1.126     brouard  7821: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7822: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7823: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7824: /*   } */
                   7825: 
                   7826:   /*#ifdef windows */
                   7827:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7828:   /*#endif */
1.225     brouard  7829:   m=pow(2,cptcoveff);
1.126     brouard  7830: 
1.274     brouard  7831:   /* diagram of the model */
                   7832:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7833:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7834:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7835:   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);
                   7836: 
                   7837:   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);
                   7838:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7839:   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);
                   7840:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7841:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7842:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7843:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7844: 
1.202     brouard  7845:   /* Contribution to likelihood */
                   7846:   /* Plot the probability implied in the likelihood */
1.223     brouard  7847:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   7848:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   7849:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   7850:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  7851: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  7852:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   7853: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  7854:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   7855:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7856:   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));
                   7857:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   7858:   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));
                   7859:   for (i=1; i<= nlstate ; i ++) {
                   7860:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   7861:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   7862:     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);
                   7863:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   7864:       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);
                   7865:     }
                   7866:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   7867:   }
                   7868:   /* 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 */               
                   7869:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   7870:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   7871:   fprintf(ficgp,"\nset out;unset log\n");
                   7872:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  7873: 
1.126     brouard  7874:   strcpy(dirfileres,optionfilefiname);
                   7875:   strcpy(optfileres,"vpl");
1.223     brouard  7876:   /* 1eme*/
1.238     brouard  7877:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   7878:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  7879:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  7880:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  7881:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  7882:          continue;
                   7883:        /* We are interested in selected combination by the resultline */
1.246     brouard  7884:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  7885:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  7886:        strcpy(gplotlabel,"(");
1.238     brouard  7887:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.332     brouard  7888:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the value of the covariate corresponding to k1 combination *\/ */
                   7889:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7890:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7891:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7892:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7893:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   7894:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  7895:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  7896:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  7897:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  7898:        }
                   7899:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  7900:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  7901:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  7902:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7903:        }
                   7904:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  7905:        /* printf("\n#\n"); */
1.238     brouard  7906:        fprintf(ficgp,"\n#\n");
                   7907:        if(invalidvarcomb[k1]){
1.260     brouard  7908:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  7909:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7910:          continue;
                   7911:        }
1.235     brouard  7912:       
1.241     brouard  7913:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7914:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  7915:        /* 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  7916:        fprintf(ficgp,"set title \"Alive state %d %s model=%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  7917:        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);
                   7918:        /* 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); */
                   7919:       /* k1-1 error should be nres-1*/
1.238     brouard  7920:        for (i=1; i<= nlstate ; i ++) {
                   7921:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7922:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   7923:        }
1.288     brouard  7924:        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  7925:        for (i=1; i<= nlstate ; i ++) {
                   7926:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7927:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7928:        } 
1.260     brouard  7929:        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  7930:        for (i=1; i<= nlstate ; i ++) {
                   7931:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7932:          else fprintf(ficgp," %%*lf (%%*lf)");
                   7933:        }  
1.265     brouard  7934:        /* 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)); */
                   7935:        
                   7936:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   7937:         if(cptcoveff ==0){
1.271     brouard  7938:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  7939:        }else{
                   7940:          kl=0;
                   7941:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7942:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7943:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  7944:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7945:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7946:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7947:            vlv= nbcode[Tvaraff[k]][lv];
                   7948:            kl++;
                   7949:            /* 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 *\/ */
                   7950:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7951:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7952:            /* ''  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*/
                   7953:            if(k==cptcoveff){
                   7954:              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], \
                   7955:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   7956:            }else{
                   7957:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   7958:              kl++;
                   7959:            }
                   7960:          } /* end covariate */
                   7961:        } /* end if no covariate */
                   7962: 
1.296     brouard  7963:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  7964:          /* 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  7965:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  7966:          if(cptcoveff ==0){
1.245     brouard  7967:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  7968:          }else{
                   7969:            kl=0;
                   7970:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  7971:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   7972:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  7973:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7974:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7975:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  7976:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   7977:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  7978:              kl++;
1.238     brouard  7979:              /* 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 *\/ */
                   7980:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7981:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7982:              /* ''  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*/
                   7983:              if(k==cptcoveff){
1.245     brouard  7984:                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  7985:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  7986:              }else{
1.332     brouard  7987:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  7988:                kl++;
                   7989:              }
                   7990:            } /* end covariate */
                   7991:          } /* end if no covariate */
1.296     brouard  7992:          if(prevbcast == 1){
1.268     brouard  7993:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   7994:            /* k1-1 error should be nres-1*/
                   7995:            for (i=1; i<= nlstate ; i ++) {
                   7996:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   7997:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   7998:            }
1.271     brouard  7999:            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  8000:            for (i=1; i<= nlstate ; i ++) {
                   8001:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8002:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8003:            } 
1.276     brouard  8004:            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  8005:            for (i=1; i<= nlstate ; i ++) {
                   8006:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8007:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8008:            } 
1.274     brouard  8009:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8010:          } /* end if backprojcast */
1.296     brouard  8011:        } /* end if prevbcast */
1.276     brouard  8012:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8013:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8014:       } /* nres */
1.201     brouard  8015:     } /* k1 */
                   8016:   } /* cpt */
1.235     brouard  8017: 
                   8018:   
1.126     brouard  8019:   /*2 eme*/
1.238     brouard  8020:   for (k1=1; k1<= m ; k1 ++){  
                   8021:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8022:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  8023:        continue;
                   8024:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8025:       strcpy(gplotlabel,"(");
1.238     brouard  8026:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8027:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8028:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.223     brouard  8029:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8030:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8031:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8032:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8033:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8034:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8035:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8036:       }
1.237     brouard  8037:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  8038:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  8039:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  8040:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.264     brouard  8041:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  8042:       }
1.264     brouard  8043:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8044:       fprintf(ficgp,"\n#\n");
1.223     brouard  8045:       if(invalidvarcomb[k1]){
                   8046:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8047:        continue;
                   8048:       }
1.219     brouard  8049:                        
1.241     brouard  8050:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8051:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8052:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8053:        if(vpopbased==0){
1.238     brouard  8054:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8055:        }else
1.238     brouard  8056:          fprintf(ficgp,"\nreplot ");
                   8057:        for (i=1; i<= nlstate+1 ; i ++) {
                   8058:          k=2*i;
1.261     brouard  8059:          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  8060:          for (j=1; j<= nlstate+1 ; j ++) {
                   8061:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8062:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8063:          }   
                   8064:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8065:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8066:          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  8067:          for (j=1; j<= nlstate+1 ; j ++) {
                   8068:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8069:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8070:          }   
                   8071:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8072:          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  8073:          for (j=1; j<= nlstate+1 ; j ++) {
                   8074:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8075:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8076:          }   
                   8077:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8078:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8079:        } /* state */
                   8080:       } /* vpopbased */
1.264     brouard  8081:       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  8082:     } /* end nres */
                   8083:   } /* k1 end 2 eme*/
                   8084:        
                   8085:        
                   8086:   /*3eme*/
                   8087:   for (k1=1; k1<= m ; k1 ++){
                   8088:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8089:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  8090:        continue;
                   8091: 
1.332     brouard  8092:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8093:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8094:        strcpy(gplotlabel,"(");
1.238     brouard  8095:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8096:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8097:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.238     brouard  8098:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8099:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8100:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8101:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8102:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8103:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8104:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8105:        }
                   8106:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8107:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
                   8108:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8109:        }       
1.264     brouard  8110:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8111:        fprintf(ficgp,"\n#\n");
                   8112:        if(invalidvarcomb[k1]){
                   8113:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8114:          continue;
                   8115:        }
                   8116:                        
                   8117:        /*       k=2+nlstate*(2*cpt-2); */
                   8118:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8119:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8120:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8121:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8122: 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  8123:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8124:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8125:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8126:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8127:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8128:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8129:                                
1.238     brouard  8130:        */
                   8131:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8132:          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  8133:          /*    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  8134:                                
1.238     brouard  8135:        } 
1.261     brouard  8136:        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  8137:       }
1.264     brouard  8138:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8139:     } /* end nres */
                   8140:   } /* end kl 3eme */
1.126     brouard  8141:   
1.223     brouard  8142:   /* 4eme */
1.201     brouard  8143:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  8144:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   8145:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8146:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  8147:        continue;
1.238     brouard  8148:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8149:        strcpy(gplotlabel,"(");
1.238     brouard  8150:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   8151:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8152:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8153:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8154:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8155:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8156:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8157:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8158:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8159:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8160:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8161:        }
                   8162:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8163:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8164:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8165:        }       
1.264     brouard  8166:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8167:        fprintf(ficgp,"\n#\n");
                   8168:        if(invalidvarcomb[k1]){
                   8169:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8170:          continue;
1.223     brouard  8171:        }
1.238     brouard  8172:       
1.241     brouard  8173:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8174:        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  8175:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8176: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8177:        k=3;
                   8178:        for (i=1; i<= nlstate ; i ++){
                   8179:          if(i==1){
                   8180:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8181:          }else{
                   8182:            fprintf(ficgp,", '' ");
                   8183:          }
                   8184:          l=(nlstate+ndeath)*(i-1)+1;
                   8185:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8186:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8187:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8188:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8189:        } /* nlstate */
1.264     brouard  8190:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8191:       } /* end cpt state*/ 
                   8192:     } /* end nres */
                   8193:   } /* end covariate k1 */  
                   8194: 
1.220     brouard  8195: /* 5eme */
1.201     brouard  8196:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  8197:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   8198:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8199:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  8200:        continue;
1.238     brouard  8201:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8202:        strcpy(gplotlabel,"(");
1.238     brouard  8203:        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);
                   8204:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8205:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8206:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
1.238     brouard  8207:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8208:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8209:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8210:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8211:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.238     brouard  8212:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8213:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.238     brouard  8214:        }
                   8215:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8216:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8217:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.238     brouard  8218:        }       
1.264     brouard  8219:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8220:        fprintf(ficgp,"\n#\n");
                   8221:        if(invalidvarcomb[k1]){
                   8222:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8223:          continue;
                   8224:        }
1.227     brouard  8225:       
1.241     brouard  8226:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8227:        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  8228:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8229: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8230:        k=3;
                   8231:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8232:          if(j==1)
                   8233:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8234:          else
                   8235:            fprintf(ficgp,", '' ");
                   8236:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8237:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8238:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8239:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8240:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8241:        } /* nlstate */
                   8242:        fprintf(ficgp,", '' ");
                   8243:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8244:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8245:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8246:          if(j < nlstate)
                   8247:            fprintf(ficgp,"$%d +",k+l);
                   8248:          else
                   8249:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8250:        }
1.264     brouard  8251:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8252:       } /* end cpt state*/ 
                   8253:     } /* end covariate */  
                   8254:   } /* end nres */
1.227     brouard  8255:   
1.220     brouard  8256: /* 6eme */
1.202     brouard  8257:   /* CV preval stable (period) for each covariate */
1.237     brouard  8258:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8259:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8260:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8261:       continue;
1.255     brouard  8262:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8263:       strcpy(gplotlabel,"(");      
1.288     brouard  8264:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  8265:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8266:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8267:        lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8268:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8269:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8270:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8271:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8272:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8273:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8274:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  8275:       }
1.237     brouard  8276:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8277:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8278:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8279:       }        
1.264     brouard  8280:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8281:       fprintf(ficgp,"\n#\n");
1.223     brouard  8282:       if(invalidvarcomb[k1]){
1.227     brouard  8283:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8284:        continue;
1.223     brouard  8285:       }
1.227     brouard  8286:       
1.241     brouard  8287:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8288:       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  8289:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8290: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8291:       k=3; /* Offset */
1.255     brouard  8292:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8293:        if(i==1)
                   8294:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8295:        else
                   8296:          fprintf(ficgp,", '' ");
1.255     brouard  8297:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8298:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8299:        for (j=2; j<= nlstate ; j ++)
                   8300:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8301:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8302:       } /* nlstate */
1.264     brouard  8303:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8304:     } /* end cpt state*/ 
                   8305:   } /* end covariate */  
1.227     brouard  8306:   
                   8307:   
1.220     brouard  8308: /* 7eme */
1.296     brouard  8309:   if(prevbcast == 1){
1.288     brouard  8310:     /* CV backward prevalence  for each covariate */
1.237     brouard  8311:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8312:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8313:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8314:        continue;
1.268     brouard  8315:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8316:        strcpy(gplotlabel,"(");      
1.288     brouard  8317:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8318:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.332     brouard  8319:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate number corresponding to k1 combination *\/ */
                   8320:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8321:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8322:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  8323:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8324:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8325:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8326:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8327:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8328:        }
1.237     brouard  8329:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8330:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8331:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8332:        }       
1.264     brouard  8333:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8334:        fprintf(ficgp,"\n#\n");
                   8335:        if(invalidvarcomb[k1]){
                   8336:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8337:          continue;
                   8338:        }
                   8339:        
1.241     brouard  8340:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8341:        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  8342:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8343: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8344:        k=3; /* Offset */
1.268     brouard  8345:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8346:          if(i==1)
                   8347:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8348:          else
                   8349:            fprintf(ficgp,", '' ");
                   8350:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8351:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8352:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8353:          /* 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  8354:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8355:          /* for (j=2; j<= nlstate ; j ++) */
                   8356:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8357:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8358:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8359:        } /* nlstate */
1.264     brouard  8360:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8361:       } /* end cpt state*/ 
                   8362:     } /* end covariate */  
1.296     brouard  8363:   } /* End if prevbcast */
1.218     brouard  8364:   
1.223     brouard  8365:   /* 8eme */
1.218     brouard  8366:   if(prevfcast==1){
1.288     brouard  8367:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8368:     
1.237     brouard  8369:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8370:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  8371:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8372:        continue;
1.211     brouard  8373:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8374:        strcpy(gplotlabel,"(");      
1.288     brouard  8375:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  8376:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8377:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8378:          lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8379:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8380:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8381:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8382:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8383:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8384:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.264     brouard  8385:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
1.227     brouard  8386:        }
1.237     brouard  8387:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8388:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8389:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8390:        }       
1.264     brouard  8391:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8392:        fprintf(ficgp,"\n#\n");
                   8393:        if(invalidvarcomb[k1]){
                   8394:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8395:          continue;
                   8396:        }
                   8397:        
                   8398:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8399:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8400:        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  8401:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8402: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8403: 
                   8404:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8405:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8406:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8407:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8408:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8409:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8410:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8411:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8412:          if(i==istart){
1.227     brouard  8413:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8414:          }else{
                   8415:            fprintf(ficgp,",\\\n '' ");
                   8416:          }
                   8417:          if(cptcoveff ==0){ /* No covariate */
                   8418:            ioffset=2; /* Age is in 2 */
                   8419:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8420:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8421:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8422:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8423:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8424:            if(i==nlstate+1){
1.270     brouard  8425:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8426:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8427:              fprintf(ficgp,",\\\n '' ");
                   8428:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8429:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8430:                     offyear,                           \
1.268     brouard  8431:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8432:            }else
1.227     brouard  8433:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8434:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8435:          }else{ /* more than 2 covariates */
1.270     brouard  8436:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8437:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8438:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8439:            iyearc=ioffset-1;
                   8440:            iagec=ioffset;
1.227     brouard  8441:            fprintf(ficgp," u %d:(",ioffset); 
                   8442:            kl=0;
                   8443:            strcpy(gplotcondition,"(");
                   8444:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8445:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8446:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8447:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8448:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8449:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8450:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8451:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8452:              kl++;
                   8453:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8454:              kl++;
                   8455:              if(k <cptcoveff && cptcoveff>1)
                   8456:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8457:            }
                   8458:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8459:            /* 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 *\/ */
                   8460:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8461:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8462:            /* ''  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*/
                   8463:            if(i==nlstate+1){
1.270     brouard  8464:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8465:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8466:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8467:              fprintf(ficgp," u %d:(",iagec); 
                   8468:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8469:                      iyearc, iagec, offyear,                           \
                   8470:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8471: /*  '' 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  8472:            }else{
                   8473:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8474:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8475:            }
                   8476:          } /* end if covariate */
                   8477:        } /* nlstate */
1.264     brouard  8478:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8479:       } /* end cpt state*/
                   8480:     } /* end covariate */
                   8481:   } /* End if prevfcast */
1.227     brouard  8482:   
1.296     brouard  8483:   if(prevbcast==1){
1.268     brouard  8484:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8485:     
                   8486:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   8487:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8488:       if(m != 1 && TKresult[nres]!= k1)
                   8489:        continue;
                   8490:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8491:        strcpy(gplotlabel,"(");      
                   8492:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   8493:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8494:          /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8495:          lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8496:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8497:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8498:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8499:          /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8500:          vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8501:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8502:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8503:        }
                   8504:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8505:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8506:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.268     brouard  8507:        }       
                   8508:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8509:        fprintf(ficgp,"\n#\n");
                   8510:        if(invalidvarcomb[k1]){
                   8511:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8512:          continue;
                   8513:        }
                   8514:        
                   8515:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8516:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8517:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8518:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8519: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8520: 
                   8521:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8522:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8523:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8524:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8525:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8526:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8527:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8528:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8529:          if(i==istart){
                   8530:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8531:          }else{
                   8532:            fprintf(ficgp,",\\\n '' ");
                   8533:          }
                   8534:          if(cptcoveff ==0){ /* No covariate */
                   8535:            ioffset=2; /* Age is in 2 */
                   8536:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8537:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8538:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8539:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8540:            fprintf(ficgp," u %d:(", ioffset); 
                   8541:            if(i==nlstate+1){
1.270     brouard  8542:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8543:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8544:              fprintf(ficgp,",\\\n '' ");
                   8545:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8546:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8547:                     offbyear,                          \
                   8548:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8549:            }else
                   8550:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8551:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8552:          }else{ /* more than 2 covariates */
1.270     brouard  8553:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8554:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8555:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8556:            iyearc=ioffset-1;
                   8557:            iagec=ioffset;
1.268     brouard  8558:            fprintf(ficgp," u %d:(",ioffset); 
                   8559:            kl=0;
                   8560:            strcpy(gplotcondition,"(");
                   8561:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8562:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8563:              lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.268     brouard  8564:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8565:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8566:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8567:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8568:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.268     brouard  8569:              kl++;
                   8570:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8571:              kl++;
                   8572:              if(k <cptcoveff && cptcoveff>1)
                   8573:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8574:            }
                   8575:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8576:            /* 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 *\/ */
                   8577:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8578:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8579:            /* ''  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*/
                   8580:            if(i==nlstate+1){
1.270     brouard  8581:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8582:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8583:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8584:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8585:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8586:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8587:                      iyearc,iagec,offbyear,                            \
                   8588:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8589: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8590:            }else{
                   8591:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8592:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8593:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8594:            }
                   8595:          } /* end if covariate */
                   8596:        } /* nlstate */
                   8597:        fprintf(ficgp,"\nset out; unset label;\n");
                   8598:       } /* end cpt state*/
                   8599:     } /* end covariate */
1.296     brouard  8600:   } /* End if prevbcast */
1.268     brouard  8601:   
1.227     brouard  8602:   
1.238     brouard  8603:   /* 9eme writing MLE parameters */
                   8604:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8605:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8606:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8607:     for(k=1; k <=(nlstate+ndeath); k++){
                   8608:       if (k != i) {
1.227     brouard  8609:        fprintf(ficgp,"#   current state %d\n",k);
                   8610:        for(j=1; j <=ncovmodel; j++){
                   8611:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8612:          jk++; 
                   8613:        }
                   8614:        fprintf(ficgp,"\n");
1.126     brouard  8615:       }
                   8616:     }
1.223     brouard  8617:   }
1.187     brouard  8618:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8619:   
1.145     brouard  8620:   /*goto avoid;*/
1.238     brouard  8621:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8622:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8623:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8624:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8625:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8626:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8627:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8628:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8629:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8630:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8631:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8632:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8633:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8634:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8635:   fprintf(ficgp,"#\n");
1.223     brouard  8636:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8637:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  8638:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  8639:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8640:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   8641:     for(k1=1; k1 <=m; k1++)  /* For each combination of covariate */
1.237     brouard  8642:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.264     brouard  8643:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  8644:        continue;
1.264     brouard  8645:       fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1);
                   8646:       strcpy(gplotlabel,"(");
1.276     brouard  8647:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.264     brouard  8648:       for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
1.332     brouard  8649:        /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8650:        lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.264     brouard  8651:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8652:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8653:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8654:        /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8655:        vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.264     brouard  8656:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   8657:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv);
                   8658:       }
1.237     brouard  8659:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.332     brouard  8660:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
                   8661:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]);
1.237     brouard  8662:       }        
1.264     brouard  8663:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8664:       fprintf(ficgp,"\n#\n");
1.264     brouard  8665:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8666:       fprintf(ficgp,"\nset key outside ");
                   8667:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8668:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8669:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8670:       if (ng==1){
                   8671:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8672:        fprintf(ficgp,"\nunset log y");
                   8673:       }else if (ng==2){
                   8674:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8675:        fprintf(ficgp,"\nset log y");
                   8676:       }else if (ng==3){
                   8677:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8678:        fprintf(ficgp,"\nset log y");
                   8679:       }else
                   8680:        fprintf(ficgp,"\nunset title ");
                   8681:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8682:       i=1;
                   8683:       for(k2=1; k2<=nlstate; k2++) {
                   8684:        k3=i;
                   8685:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8686:          if (k != k2){
                   8687:            switch( ng) {
                   8688:            case 1:
                   8689:              if(nagesqr==0)
                   8690:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8691:              else /* nagesqr =1 */
                   8692:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8693:              break;
                   8694:            case 2: /* ng=2 */
                   8695:              if(nagesqr==0)
                   8696:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8697:              else /* nagesqr =1 */
                   8698:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8699:              break;
                   8700:            case 3:
                   8701:              if(nagesqr==0)
                   8702:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8703:              else /* nagesqr =1 */
                   8704:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8705:              break;
                   8706:            }
                   8707:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8708:            ijp=1; /* product no age */
                   8709:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8710:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8711:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8712:              switch(Typevar[j]){
                   8713:              case 1:
                   8714:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8715:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8716:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8717:                      if(DummyV[j]==0){/* Bug valgrind */
                   8718:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8719:                      }else{ /* quantitative */
                   8720:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8721:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8722:                      }
                   8723:                      ij++;
1.268     brouard  8724:                    }
1.237     brouard  8725:                  }
1.329     brouard  8726:                }
                   8727:                break;
                   8728:              case 2:
                   8729:                if(cptcovprod >0){
                   8730:                  if(j==Tprod[ijp]) { /* */ 
                   8731:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8732:                    if(ijp <=cptcovprod) { /* Product */
                   8733:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8734:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8735:                          /* 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)]); */
                   8736:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8737:                        }else{ /* Vn is dummy and Vm is quanti */
                   8738:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8739:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8740:                        }
                   8741:                      }else{ /* Vn*Vm Vn is quanti */
                   8742:                        if(DummyV[Tvard[ijp][2]]==0){
                   8743:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8744:                        }else{ /* Both quanti */
                   8745:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8746:                        }
1.268     brouard  8747:                      }
1.329     brouard  8748:                      ijp++;
1.237     brouard  8749:                    }
1.329     brouard  8750:                  } /* end Tprod */
                   8751:                }
                   8752:                break;
                   8753:              case 0:
                   8754:                /* simple covariate */
1.264     brouard  8755:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8756:                if(Dummy[j]==0){
                   8757:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8758:                }else{ /* quantitative */
                   8759:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8760:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8761:                }
1.329     brouard  8762:               /* end simple */
                   8763:                break;
                   8764:              default:
                   8765:                break;
                   8766:              } /* end switch */
1.237     brouard  8767:            } /* end j */
1.329     brouard  8768:          }else{ /* k=k2 */
                   8769:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8770:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8771:            }else
                   8772:              i=i-ncovmodel;
1.223     brouard  8773:          }
1.227     brouard  8774:          
1.223     brouard  8775:          if(ng != 1){
                   8776:            fprintf(ficgp,")/(1");
1.227     brouard  8777:            
1.264     brouard  8778:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8779:              if(nagesqr==0)
1.264     brouard  8780:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8781:              else /* nagesqr =1 */
1.264     brouard  8782:                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  8783:               
1.223     brouard  8784:              ij=1;
1.329     brouard  8785:              ijp=1;
                   8786:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   8787:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   8788:                switch(Typevar[j]){
                   8789:                case 1:
                   8790:                  if(cptcovage >0){ 
                   8791:                    if(j==Tage[ij]) { /* Bug valgrind */
                   8792:                      if(ij <=cptcovage) { /* Bug valgrind */
                   8793:                        if(DummyV[j]==0){/* Bug valgrind */
                   8794:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   8795:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   8796:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   8797:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   8798:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8799:                        }else{ /* quantitative */
                   8800:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8801:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8802:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   8803:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8804:                        }
                   8805:                        ij++;
                   8806:                      }
                   8807:                    }
                   8808:                  }
                   8809:                  break;
                   8810:                case 2:
                   8811:                  if(cptcovprod >0){
                   8812:                    if(j==Tprod[ijp]) { /* */ 
                   8813:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8814:                      if(ijp <=cptcovprod) { /* Product */
                   8815:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8816:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8817:                            /* 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)]); */
                   8818:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8819:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   8820:                          }else{ /* Vn is dummy and Vm is quanti */
                   8821:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8822:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8823:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8824:                          }
                   8825:                        }else{ /* Vn*Vm Vn is quanti */
                   8826:                          if(DummyV[Tvard[ijp][2]]==0){
                   8827:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8828:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   8829:                          }else{ /* Both quanti */
                   8830:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8831:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8832:                          } 
                   8833:                        }
                   8834:                        ijp++;
                   8835:                      }
                   8836:                    } /* end Tprod */
                   8837:                  } /* end if */
                   8838:                  break;
                   8839:                case 0: 
                   8840:                  /* simple covariate */
                   8841:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   8842:                  if(Dummy[j]==0){
                   8843:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8844:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   8845:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   8846:                  }else{ /* quantitative */
                   8847:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   8848:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   8849:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8850:                  }
                   8851:                  /* end simple */
                   8852:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   8853:                  break;
                   8854:                default:
                   8855:                  break;
                   8856:                } /* end switch */
1.223     brouard  8857:              }
                   8858:              fprintf(ficgp,")");
                   8859:            }
                   8860:            fprintf(ficgp,")");
                   8861:            if(ng ==2)
1.276     brouard  8862:              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  8863:            else /* ng= 3 */
1.276     brouard  8864:              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  8865:           }else{ /* end ng <> 1 */
1.223     brouard  8866:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  8867:              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  8868:          }
                   8869:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   8870:            fprintf(ficgp,",");
                   8871:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   8872:            fprintf(ficgp,",");
                   8873:          i=i+ncovmodel;
                   8874:        } /* end k */
                   8875:       } /* end k2 */
1.276     brouard  8876:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   8877:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.264     brouard  8878:     } /* end k1 */
1.223     brouard  8879:   } /* end ng */
                   8880:   /* avoid: */
                   8881:   fflush(ficgp); 
1.126     brouard  8882: }  /* end gnuplot */
                   8883: 
                   8884: 
                   8885: /*************** Moving average **************/
1.219     brouard  8886: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  8887:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  8888:    
1.222     brouard  8889:    int i, cpt, cptcod;
                   8890:    int modcovmax =1;
                   8891:    int mobilavrange, mob;
                   8892:    int iage=0;
1.288     brouard  8893:    int firstA1=0, firstA2=0;
1.222     brouard  8894: 
1.266     brouard  8895:    double sum=0., sumr=0.;
1.222     brouard  8896:    double age;
1.266     brouard  8897:    double *sumnewp, *sumnewm, *sumnewmr;
                   8898:    double *agemingood, *agemaxgood; 
                   8899:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  8900:   
                   8901:   
1.278     brouard  8902:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   8903:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  8904: 
                   8905:    sumnewp = vector(1,ncovcombmax);
                   8906:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  8907:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  8908:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  8909:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  8910:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  8911:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  8912: 
                   8913:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  8914:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  8915:      sumnewp[cptcod]=0.;
1.266     brouard  8916:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   8917:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  8918:    }
                   8919:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   8920:   
1.266     brouard  8921:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   8922:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  8923:      else mobilavrange=mobilav;
                   8924:      for (age=bage; age<=fage; age++)
                   8925:        for (i=1; i<=nlstate;i++)
                   8926:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   8927:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   8928:      /* We keep the original values on the extreme ages bage, fage and for 
                   8929:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   8930:        we use a 5 terms etc. until the borders are no more concerned. 
                   8931:      */ 
                   8932:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   8933:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  8934:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   8935:           sumnewm[cptcod]=0.;
                   8936:           for (i=1; i<=nlstate;i++){
1.222     brouard  8937:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   8938:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   8939:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   8940:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   8941:             }
                   8942:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  8943:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8944:           } /* end i */
                   8945:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   8946:         } /* end cptcod */
1.222     brouard  8947:        }/* end age */
                   8948:      }/* end mob */
1.266     brouard  8949:    }else{
                   8950:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  8951:      return -1;
1.266     brouard  8952:    }
                   8953: 
                   8954:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  8955:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   8956:      if(invalidvarcomb[cptcod]){
                   8957:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   8958:        continue;
                   8959:      }
1.219     brouard  8960: 
1.266     brouard  8961:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   8962:        sumnewm[cptcod]=0.;
                   8963:        sumnewmr[cptcod]=0.;
                   8964:        for (i=1; i<=nlstate;i++){
                   8965:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8966:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8967:        }
                   8968:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8969:         agemingoodr[cptcod]=age;
                   8970:        }
                   8971:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   8972:           agemingood[cptcod]=age;
                   8973:        }
                   8974:      } /* age */
                   8975:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  8976:        sumnewm[cptcod]=0.;
1.266     brouard  8977:        sumnewmr[cptcod]=0.;
1.222     brouard  8978:        for (i=1; i<=nlstate;i++){
                   8979:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  8980:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8981:        }
                   8982:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   8983:         agemaxgoodr[cptcod]=age;
1.222     brouard  8984:        }
                   8985:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  8986:         agemaxgood[cptcod]=age;
                   8987:        }
                   8988:      } /* age */
                   8989:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   8990:      /* but they will change */
1.288     brouard  8991:      firstA1=0;firstA2=0;
1.266     brouard  8992:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   8993:        sumnewm[cptcod]=0.;
                   8994:        sumnewmr[cptcod]=0.;
                   8995:        for (i=1; i<=nlstate;i++){
                   8996:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   8997:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   8998:        }
                   8999:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9000:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9001:           agemaxgoodr[cptcod]=age;  /* age min */
                   9002:           for (i=1; i<=nlstate;i++)
                   9003:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9004:         }else{ /* bad we change the value with the values of good ages */
                   9005:           for (i=1; i<=nlstate;i++){
                   9006:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9007:           } /* i */
                   9008:         } /* end bad */
                   9009:        }else{
                   9010:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9011:           agemaxgood[cptcod]=age;
                   9012:         }else{ /* bad we change the value with the values of good ages */
                   9013:           for (i=1; i<=nlstate;i++){
                   9014:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9015:           } /* i */
                   9016:         } /* end bad */
                   9017:        }/* end else */
                   9018:        sum=0.;sumr=0.;
                   9019:        for (i=1; i<=nlstate;i++){
                   9020:         sum+=mobaverage[(int)age][i][cptcod];
                   9021:         sumr+=probs[(int)age][i][cptcod];
                   9022:        }
                   9023:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9024:         if(!firstA1){
                   9025:           firstA1=1;
                   9026:           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);
                   9027:         }
                   9028:         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  9029:        } /* end bad */
                   9030:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9031:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9032:         if(!firstA2){
                   9033:           firstA2=1;
                   9034:           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);
                   9035:         }
                   9036:         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  9037:        } /* end bad */
                   9038:      }/* age */
1.266     brouard  9039: 
                   9040:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9041:        sumnewm[cptcod]=0.;
1.266     brouard  9042:        sumnewmr[cptcod]=0.;
1.222     brouard  9043:        for (i=1; i<=nlstate;i++){
                   9044:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9045:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9046:        } 
                   9047:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9048:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9049:           agemingoodr[cptcod]=age;
                   9050:           for (i=1; i<=nlstate;i++)
                   9051:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9052:         }else{ /* bad we change the value with the values of good ages */
                   9053:           for (i=1; i<=nlstate;i++){
                   9054:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9055:           } /* i */
                   9056:         } /* end bad */
                   9057:        }else{
                   9058:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9059:           agemingood[cptcod]=age;
                   9060:         }else{ /* bad */
                   9061:           for (i=1; i<=nlstate;i++){
                   9062:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9063:           } /* i */
                   9064:         } /* end bad */
                   9065:        }/* end else */
                   9066:        sum=0.;sumr=0.;
                   9067:        for (i=1; i<=nlstate;i++){
                   9068:         sum+=mobaverage[(int)age][i][cptcod];
                   9069:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9070:        }
1.266     brouard  9071:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9072:         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  9073:        } /* end bad */
                   9074:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9075:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9076:         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  9077:        } /* end bad */
                   9078:      }/* age */
1.266     brouard  9079: 
1.222     brouard  9080:                
                   9081:      for (age=bage; age<=fage; age++){
1.235     brouard  9082:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9083:        sumnewp[cptcod]=0.;
                   9084:        sumnewm[cptcod]=0.;
                   9085:        for (i=1; i<=nlstate;i++){
                   9086:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9087:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9088:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9089:        }
                   9090:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9091:      }
                   9092:      /* printf("\n"); */
                   9093:      /* } */
1.266     brouard  9094: 
1.222     brouard  9095:      /* brutal averaging */
1.266     brouard  9096:      /* for (i=1; i<=nlstate;i++){ */
                   9097:      /*   for (age=1; age<=bage; age++){ */
                   9098:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9099:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9100:      /*   }     */
                   9101:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9102:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9103:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9104:      /*   } */
                   9105:      /* } /\* end i status *\/ */
                   9106:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9107:      /*   for (age=1; age<=AGESUP; age++){ */
                   9108:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9109:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9110:      /*   } */
                   9111:      /* } */
1.222     brouard  9112:    }/* end cptcod */
1.266     brouard  9113:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9114:    free_vector(agemaxgood,1, ncovcombmax);
                   9115:    free_vector(agemingood,1, ncovcombmax);
                   9116:    free_vector(agemingoodr,1, ncovcombmax);
                   9117:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9118:    free_vector(sumnewm,1, ncovcombmax);
                   9119:    free_vector(sumnewp,1, ncovcombmax);
                   9120:    return 0;
                   9121:  }/* End movingaverage */
1.218     brouard  9122:  
1.126     brouard  9123: 
1.296     brouard  9124:  
1.126     brouard  9125: /************** Forecasting ******************/
1.296     brouard  9126: /* 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)*/
                   9127: 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){
                   9128:   /* dateintemean, mean date of interviews
                   9129:      dateprojd, year, month, day of starting projection 
                   9130:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9131:      agemin, agemax range of age
                   9132:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9133:   */
1.296     brouard  9134:   /* double anprojd, mprojd, jprojd; */
                   9135:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9136:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9137:   double agec; /* generic age */
1.296     brouard  9138:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9139:   double *popeffectif,*popcount;
                   9140:   double ***p3mat;
1.218     brouard  9141:   /* double ***mobaverage; */
1.126     brouard  9142:   char fileresf[FILENAMELENGTH];
                   9143: 
                   9144:   agelim=AGESUP;
1.211     brouard  9145:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9146:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9147:      We still use firstpass and lastpass as another selection.
                   9148:   */
1.214     brouard  9149:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9150:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9151:  
1.201     brouard  9152:   strcpy(fileresf,"F_"); 
                   9153:   strcat(fileresf,fileresu);
1.126     brouard  9154:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9155:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9156:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9157:   }
1.235     brouard  9158:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9159:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9160: 
1.225     brouard  9161:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9162: 
                   9163: 
                   9164:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9165:   if (stepm<=12) stepsize=1;
                   9166:   if(estepm < stepm){
                   9167:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9168:   }
1.270     brouard  9169:   else{
                   9170:     hstepm=estepm;   
                   9171:   }
                   9172:   if(estepm > stepm){ /* Yes every two year */
                   9173:     stepsize=2;
                   9174:   }
1.296     brouard  9175:   hstepm=hstepm/stepm;
1.126     brouard  9176: 
1.296     brouard  9177:   
                   9178:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9179:   /*                              fractional in yp1 *\/ */
                   9180:   /* aintmean=yp; */
                   9181:   /* yp2=modf((yp1*12),&yp); */
                   9182:   /* mintmean=yp; */
                   9183:   /* yp1=modf((yp2*30.5),&yp); */
                   9184:   /* jintmean=yp; */
                   9185:   /* if(jintmean==0) jintmean=1; */
                   9186:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9187: 
1.296     brouard  9188: 
                   9189:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9190:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9191:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9192:   i1=pow(2,cptcoveff);
1.126     brouard  9193:   if (cptcovn < 1){i1=1;}
                   9194:   
1.296     brouard  9195:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9196:   
                   9197:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9198:   
1.126     brouard  9199: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9200:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9201:     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  9202:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9203:       continue;
1.227     brouard  9204:     if(invalidvarcomb[k]){
                   9205:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9206:       continue;
                   9207:     }
                   9208:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9209:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9210:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9211:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9212:     }
1.235     brouard  9213:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9214:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9215:     }
1.227     brouard  9216:     fprintf(ficresf," yearproj age");
                   9217:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9218:       for(i=1; i<=nlstate;i++)               
                   9219:        fprintf(ficresf," p%d%d",i,j);
                   9220:       fprintf(ficresf," wp.%d",j);
                   9221:     }
1.296     brouard  9222:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9223:       fprintf(ficresf,"\n");
1.296     brouard  9224:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9225:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9226:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9227:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9228:        nhstepm = nhstepm/hstepm; 
                   9229:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9230:        oldm=oldms;savm=savms;
1.268     brouard  9231:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9232:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9233:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9234:        for (h=0; h<=nhstepm; h++){
                   9235:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9236:            break;
                   9237:          }
                   9238:        }
                   9239:        fprintf(ficresf,"\n");
                   9240:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9241:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9242:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9243:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9244:        
                   9245:        for(j=1; j<=nlstate+ndeath;j++) {
                   9246:          ppij=0.;
                   9247:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9248:            if (mobilav>=1)
                   9249:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9250:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9251:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9252:            }
1.268     brouard  9253:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9254:          } /* end i */
                   9255:          fprintf(ficresf," %.3f", ppij);
                   9256:        }/* end j */
1.227     brouard  9257:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9258:       } /* end agec */
1.266     brouard  9259:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9260:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9261:     } /* end yearp */
                   9262:   } /* end  k */
1.219     brouard  9263:        
1.126     brouard  9264:   fclose(ficresf);
1.215     brouard  9265:   printf("End of Computing forecasting \n");
                   9266:   fprintf(ficlog,"End of Computing forecasting\n");
                   9267: 
1.126     brouard  9268: }
                   9269: 
1.269     brouard  9270: /************** Back Forecasting ******************/
1.296     brouard  9271:  /* 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){ */
                   9272:  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){
                   9273:   /* back1, year, month, day of starting backprojection
1.267     brouard  9274:      agemin, agemax range of age
                   9275:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9276:      anback2 year of end of backprojection (same day and month as back1).
                   9277:      prevacurrent and prev are prevalences.
1.267     brouard  9278:   */
                   9279:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9280:   double agec; /* generic age */
1.302     brouard  9281:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9282:   double *popeffectif,*popcount;
                   9283:   double ***p3mat;
                   9284:   /* double ***mobaverage; */
                   9285:   char fileresfb[FILENAMELENGTH];
                   9286:  
1.268     brouard  9287:   agelim=AGEINF;
1.267     brouard  9288:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9289:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9290:      We still use firstpass and lastpass as another selection.
                   9291:   */
                   9292:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9293:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9294: 
                   9295:   /*Do we need to compute prevalence again?*/
                   9296: 
                   9297:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9298:   
                   9299:   strcpy(fileresfb,"FB_");
                   9300:   strcat(fileresfb,fileresu);
                   9301:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9302:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9303:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9304:   }
                   9305:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9306:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9307:   
                   9308:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9309:   
                   9310:    
                   9311:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9312:   if (stepm<=12) stepsize=1;
                   9313:   if(estepm < stepm){
                   9314:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9315:   }
1.270     brouard  9316:   else{
                   9317:     hstepm=estepm;   
                   9318:   }
                   9319:   if(estepm >= stepm){ /* Yes every two year */
                   9320:     stepsize=2;
                   9321:   }
1.267     brouard  9322:   
                   9323:   hstepm=hstepm/stepm;
1.296     brouard  9324:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9325:   /*                              fractional in yp1 *\/ */
                   9326:   /* aintmean=yp; */
                   9327:   /* yp2=modf((yp1*12),&yp); */
                   9328:   /* mintmean=yp; */
                   9329:   /* yp1=modf((yp2*30.5),&yp); */
                   9330:   /* jintmean=yp; */
                   9331:   /* if(jintmean==0) jintmean=1; */
                   9332:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9333:   
                   9334:   i1=pow(2,cptcoveff);
                   9335:   if (cptcovn < 1){i1=1;}
                   9336:   
1.296     brouard  9337:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9338:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9339:   
                   9340:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9341:   
                   9342:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9343:   for(k=1; k<=i1;k++){
                   9344:     if(i1 != 1 && TKresult[nres]!= k)
                   9345:       continue;
                   9346:     if(invalidvarcomb[k]){
                   9347:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9348:       continue;
                   9349:     }
1.268     brouard  9350:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9351:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9352:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9353:     }
                   9354:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9355:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9356:     }
                   9357:     fprintf(ficresfb," yearbproj age");
                   9358:     for(j=1; j<=nlstate+ndeath;j++){
                   9359:       for(i=1; i<=nlstate;i++)
1.268     brouard  9360:        fprintf(ficresfb," b%d%d",i,j);
                   9361:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9362:     }
1.296     brouard  9363:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9364:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9365:       fprintf(ficresfb,"\n");
1.296     brouard  9366:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9367:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9368:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9369:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9370:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9371:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9372:        nhstepm = nhstepm/hstepm;
                   9373:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9374:        oldm=oldms;savm=savms;
1.268     brouard  9375:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9376:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9377:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9378:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9379:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9380:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9381:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9382:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9383:            break;
                   9384:          }
                   9385:        }
                   9386:        fprintf(ficresfb,"\n");
                   9387:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9388:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9389:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9390:        for(i=1; i<=nlstate+ndeath;i++) {
                   9391:          ppij=0.;ppi=0.;
                   9392:          for(j=1; j<=nlstate;j++) {
                   9393:            /* if (mobilav==1) */
1.269     brouard  9394:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9395:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9396:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9397:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9398:              /* else { */
                   9399:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9400:              /* } */
1.268     brouard  9401:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9402:          } /* end j */
                   9403:          if(ppi <0.99){
                   9404:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9405:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9406:          }
                   9407:          fprintf(ficresfb," %.3f", ppij);
                   9408:        }/* end j */
1.267     brouard  9409:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9410:       } /* end agec */
                   9411:     } /* end yearp */
                   9412:   } /* end k */
1.217     brouard  9413:   
1.267     brouard  9414:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9415:   
1.267     brouard  9416:   fclose(ficresfb);
                   9417:   printf("End of Computing Back forecasting \n");
                   9418:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9419:        
1.267     brouard  9420: }
1.217     brouard  9421: 
1.269     brouard  9422: /* Variance of prevalence limit: varprlim */
                   9423:  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  9424:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9425:  
                   9426:    char fileresvpl[FILENAMELENGTH];  
                   9427:    FILE *ficresvpl;
                   9428:    double **oldm, **savm;
                   9429:    double **varpl; /* Variances of prevalence limits by age */   
                   9430:    int i1, k, nres, j ;
                   9431:    
                   9432:     strcpy(fileresvpl,"VPL_");
                   9433:     strcat(fileresvpl,fileresu);
                   9434:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9435:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9436:       exit(0);
                   9437:     }
1.288     brouard  9438:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9439:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9440:     
                   9441:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9442:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9443:     
                   9444:     i1=pow(2,cptcoveff);
                   9445:     if (cptcovn < 1){i1=1;}
                   9446: 
                   9447:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9448:       for(k=1; k<=i1;k++){ /* We find the combination equivalent to result line values of dummies */
1.269     brouard  9449:       if(i1 != 1 && TKresult[nres]!= k)
                   9450:        continue;
                   9451:       fprintf(ficresvpl,"\n#****** ");
                   9452:       printf("\n#****** ");
                   9453:       fprintf(ficlog,"\n#****** ");
                   9454:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9455:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9456:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9457:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9458:       }
                   9459:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9460:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9461:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9462:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9463:       }        
                   9464:       fprintf(ficresvpl,"******\n");
                   9465:       printf("******\n");
                   9466:       fprintf(ficlog,"******\n");
                   9467:       
                   9468:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9469:       oldm=oldms;savm=savms;
                   9470:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9471:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9472:       /*}*/
                   9473:     }
                   9474:     
                   9475:     fclose(ficresvpl);
1.288     brouard  9476:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9477:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9478: 
                   9479:  }
                   9480: /* Variance of back prevalence: varbprlim */
                   9481:  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){
                   9482:       /*------- Variance of back (stable) prevalence------*/
                   9483: 
                   9484:    char fileresvbl[FILENAMELENGTH];  
                   9485:    FILE  *ficresvbl;
                   9486: 
                   9487:    double **oldm, **savm;
                   9488:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9489:    int i1, k, nres, j ;
                   9490: 
                   9491:    strcpy(fileresvbl,"VBL_");
                   9492:    strcat(fileresvbl,fileresu);
                   9493:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9494:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9495:      exit(0);
                   9496:    }
                   9497:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9498:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9499:    
                   9500:    
                   9501:    i1=pow(2,cptcoveff);
                   9502:    if (cptcovn < 1){i1=1;}
                   9503:    
                   9504:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9505:      for(k=1; k<=i1;k++){
                   9506:        if(i1 != 1 && TKresult[nres]!= k)
                   9507:         continue;
                   9508:        fprintf(ficresvbl,"\n#****** ");
                   9509:        printf("\n#****** ");
                   9510:        fprintf(ficlog,"\n#****** ");
                   9511:        for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9512:         fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9513:         fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   9514:         printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.269     brouard  9515:        }
                   9516:        for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  9517:         printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9518:         fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   9519:         fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.269     brouard  9520:        }
                   9521:        fprintf(ficresvbl,"******\n");
                   9522:        printf("******\n");
                   9523:        fprintf(ficlog,"******\n");
                   9524:        
                   9525:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9526:        oldm=oldms;savm=savms;
                   9527:        
                   9528:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9529:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9530:        /*}*/
                   9531:      }
                   9532:    
                   9533:    fclose(ficresvbl);
                   9534:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9535:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9536: 
                   9537:  } /* End of varbprlim */
                   9538: 
1.126     brouard  9539: /************** Forecasting *****not tested NB*************/
1.227     brouard  9540: /* 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  9541:   
1.227     brouard  9542: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9543: /*   int *popage; */
                   9544: /*   double calagedatem, agelim, kk1, kk2; */
                   9545: /*   double *popeffectif,*popcount; */
                   9546: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9547: /*   /\* double ***mobaverage; *\/ */
                   9548: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9549: 
1.227     brouard  9550: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9551: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9552: /*   agelim=AGESUP; */
                   9553: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9554:   
1.227     brouard  9555: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9556:   
                   9557:   
1.227     brouard  9558: /*   strcpy(filerespop,"POP_");  */
                   9559: /*   strcat(filerespop,fileresu); */
                   9560: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9561: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9562: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9563: /*   } */
                   9564: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9565: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9566: 
1.227     brouard  9567: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9568: 
1.227     brouard  9569: /*   /\* if (mobilav!=0) { *\/ */
                   9570: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9571: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9572: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9573: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9574: /*   /\*   } *\/ */
                   9575: /*   /\* } *\/ */
1.126     brouard  9576: 
1.227     brouard  9577: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9578: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9579:   
1.227     brouard  9580: /*   agelim=AGESUP; */
1.126     brouard  9581:   
1.227     brouard  9582: /*   hstepm=1; */
                   9583: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9584:        
1.227     brouard  9585: /*   if (popforecast==1) { */
                   9586: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9587: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9588: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9589: /*     }  */
                   9590: /*     popage=ivector(0,AGESUP); */
                   9591: /*     popeffectif=vector(0,AGESUP); */
                   9592: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9593:     
1.227     brouard  9594: /*     i=1;    */
                   9595: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9596:     
1.227     brouard  9597: /*     imx=i; */
                   9598: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9599: /*   } */
1.218     brouard  9600:   
1.227     brouard  9601: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9602: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9603: /*       k=k+1; */
                   9604: /*       fprintf(ficrespop,"\n#******"); */
                   9605: /*       for(j=1;j<=cptcoveff;j++) { */
                   9606: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9607: /*       } */
                   9608: /*       fprintf(ficrespop,"******\n"); */
                   9609: /*       fprintf(ficrespop,"# Age"); */
                   9610: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9611: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9612:       
1.227     brouard  9613: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9614: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9615:        
1.227     brouard  9616: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9617: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9618: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9619:          
1.227     brouard  9620: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9621: /*       oldm=oldms;savm=savms; */
                   9622: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9623:          
1.227     brouard  9624: /*       for (h=0; h<=nhstepm; h++){ */
                   9625: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9626: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9627: /*         }  */
                   9628: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9629: /*           kk1=0.;kk2=0; */
                   9630: /*           for(i=1; i<=nlstate;i++) {               */
                   9631: /*             if (mobilav==1)  */
                   9632: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9633: /*             else { */
                   9634: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9635: /*             } */
                   9636: /*           } */
                   9637: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9638: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9639: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9640: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9641: /*           } */
                   9642: /*         } */
                   9643: /*         for(i=1; i<=nlstate;i++){ */
                   9644: /*           kk1=0.; */
                   9645: /*           for(j=1; j<=nlstate;j++){ */
                   9646: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9647: /*           } */
                   9648: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9649: /*         } */
1.218     brouard  9650:            
1.227     brouard  9651: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9652: /*           for(j=1; j<=nlstate;j++)  */
                   9653: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9654: /*       } */
                   9655: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9656: /*     } */
                   9657: /*       } */
1.218     brouard  9658:       
1.227     brouard  9659: /*       /\******\/ */
1.218     brouard  9660:       
1.227     brouard  9661: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9662: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9663: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9664: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9665: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9666:          
1.227     brouard  9667: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9668: /*       oldm=oldms;savm=savms; */
                   9669: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9670: /*       for (h=0; h<=nhstepm; h++){ */
                   9671: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9672: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9673: /*         }  */
                   9674: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9675: /*           kk1=0.;kk2=0; */
                   9676: /*           for(i=1; i<=nlstate;i++) {               */
                   9677: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9678: /*           } */
                   9679: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9680: /*         } */
                   9681: /*       } */
                   9682: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9683: /*     } */
                   9684: /*       } */
                   9685: /*     }  */
                   9686: /*   } */
1.218     brouard  9687:   
1.227     brouard  9688: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9689:   
1.227     brouard  9690: /*   if (popforecast==1) { */
                   9691: /*     free_ivector(popage,0,AGESUP); */
                   9692: /*     free_vector(popeffectif,0,AGESUP); */
                   9693: /*     free_vector(popcount,0,AGESUP); */
                   9694: /*   } */
                   9695: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9696: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9697: /*   fclose(ficrespop); */
                   9698: /* } /\* End of popforecast *\/ */
1.218     brouard  9699:  
1.126     brouard  9700: int fileappend(FILE *fichier, char *optionfich)
                   9701: {
                   9702:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9703:     printf("Problem with file: %s\n", optionfich);
                   9704:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9705:     return (0);
                   9706:   }
                   9707:   fflush(fichier);
                   9708:   return (1);
                   9709: }
                   9710: 
                   9711: 
                   9712: /**************** function prwizard **********************/
                   9713: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9714: {
                   9715: 
                   9716:   /* Wizard to print covariance matrix template */
                   9717: 
1.164     brouard  9718:   char ca[32], cb[32];
                   9719:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9720:   int numlinepar;
                   9721: 
                   9722:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9723:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9724:   for(i=1; i <=nlstate; i++){
                   9725:     jj=0;
                   9726:     for(j=1; j <=nlstate+ndeath; j++){
                   9727:       if(j==i) continue;
                   9728:       jj++;
                   9729:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9730:       printf("%1d%1d",i,j);
                   9731:       fprintf(ficparo,"%1d%1d",i,j);
                   9732:       for(k=1; k<=ncovmodel;k++){
                   9733:        /*        printf(" %lf",param[i][j][k]); */
                   9734:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9735:        printf(" 0.");
                   9736:        fprintf(ficparo," 0.");
                   9737:       }
                   9738:       printf("\n");
                   9739:       fprintf(ficparo,"\n");
                   9740:     }
                   9741:   }
                   9742:   printf("# Scales (for hessian or gradient estimation)\n");
                   9743:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9744:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9745:   for(i=1; i <=nlstate; i++){
                   9746:     jj=0;
                   9747:     for(j=1; j <=nlstate+ndeath; j++){
                   9748:       if(j==i) continue;
                   9749:       jj++;
                   9750:       fprintf(ficparo,"%1d%1d",i,j);
                   9751:       printf("%1d%1d",i,j);
                   9752:       fflush(stdout);
                   9753:       for(k=1; k<=ncovmodel;k++){
                   9754:        /*      printf(" %le",delti3[i][j][k]); */
                   9755:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9756:        printf(" 0.");
                   9757:        fprintf(ficparo," 0.");
                   9758:       }
                   9759:       numlinepar++;
                   9760:       printf("\n");
                   9761:       fprintf(ficparo,"\n");
                   9762:     }
                   9763:   }
                   9764:   printf("# Covariance matrix\n");
                   9765: /* # 121 Var(a12)\n\ */
                   9766: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9767: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9768: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9769: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9770: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9771: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9772: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9773:   fflush(stdout);
                   9774:   fprintf(ficparo,"# Covariance matrix\n");
                   9775:   /* # 121 Var(a12)\n\ */
                   9776:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9777:   /* #   ...\n\ */
                   9778:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   9779:   
                   9780:   for(itimes=1;itimes<=2;itimes++){
                   9781:     jj=0;
                   9782:     for(i=1; i <=nlstate; i++){
                   9783:       for(j=1; j <=nlstate+ndeath; j++){
                   9784:        if(j==i) continue;
                   9785:        for(k=1; k<=ncovmodel;k++){
                   9786:          jj++;
                   9787:          ca[0]= k+'a'-1;ca[1]='\0';
                   9788:          if(itimes==1){
                   9789:            printf("#%1d%1d%d",i,j,k);
                   9790:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   9791:          }else{
                   9792:            printf("%1d%1d%d",i,j,k);
                   9793:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   9794:            /*  printf(" %.5le",matcov[i][j]); */
                   9795:          }
                   9796:          ll=0;
                   9797:          for(li=1;li <=nlstate; li++){
                   9798:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   9799:              if(lj==li) continue;
                   9800:              for(lk=1;lk<=ncovmodel;lk++){
                   9801:                ll++;
                   9802:                if(ll<=jj){
                   9803:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   9804:                  if(ll<jj){
                   9805:                    if(itimes==1){
                   9806:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9807:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9808:                    }else{
                   9809:                      printf(" 0.");
                   9810:                      fprintf(ficparo," 0.");
                   9811:                    }
                   9812:                  }else{
                   9813:                    if(itimes==1){
                   9814:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   9815:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   9816:                    }else{
                   9817:                      printf(" 0.");
                   9818:                      fprintf(ficparo," 0.");
                   9819:                    }
                   9820:                  }
                   9821:                }
                   9822:              } /* end lk */
                   9823:            } /* end lj */
                   9824:          } /* end li */
                   9825:          printf("\n");
                   9826:          fprintf(ficparo,"\n");
                   9827:          numlinepar++;
                   9828:        } /* end k*/
                   9829:       } /*end j */
                   9830:     } /* end i */
                   9831:   } /* end itimes */
                   9832: 
                   9833: } /* end of prwizard */
                   9834: /******************* Gompertz Likelihood ******************************/
                   9835: double gompertz(double x[])
                   9836: { 
1.302     brouard  9837:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  9838:   int i,n=0; /* n is the size of the sample */
                   9839: 
1.220     brouard  9840:   for (i=1;i<=imx ; i++) {
1.126     brouard  9841:     sump=sump+weight[i];
                   9842:     /*    sump=sump+1;*/
                   9843:     num=num+1;
                   9844:   }
1.302     brouard  9845:   L=0.0;
                   9846:   /* agegomp=AGEGOMP; */
1.126     brouard  9847:   /* for (i=0; i<=imx; i++) 
                   9848:      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]);*/
                   9849: 
1.302     brouard  9850:   for (i=1;i<=imx ; i++) {
                   9851:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   9852:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   9853:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   9854:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   9855:      * +
                   9856:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   9857:      */
                   9858:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   9859:        if (cens[i] == 1){
                   9860:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   9861:        } else if (cens[i] == 0){
1.126     brouard  9862:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  9863:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   9864:       } else
                   9865:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  9866:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  9867:        L=L+A*weight[i];
1.126     brouard  9868:        /*      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  9869:      }
                   9870:   }
1.126     brouard  9871: 
1.302     brouard  9872:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  9873:  
                   9874:   return -2*L*num/sump;
                   9875: }
                   9876: 
1.136     brouard  9877: #ifdef GSL
                   9878: /******************* Gompertz_f Likelihood ******************************/
                   9879: double gompertz_f(const gsl_vector *v, void *params)
                   9880: { 
1.302     brouard  9881:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  9882:   double *x= (double *) v->data;
                   9883:   int i,n=0; /* n is the size of the sample */
                   9884: 
                   9885:   for (i=0;i<=imx-1 ; i++) {
                   9886:     sump=sump+weight[i];
                   9887:     /*    sump=sump+1;*/
                   9888:     num=num+1;
                   9889:   }
                   9890:  
                   9891:  
                   9892:   /* for (i=0; i<=imx; i++) 
                   9893:      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]);*/
                   9894:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   9895:   for (i=1;i<=imx ; i++)
                   9896:     {
                   9897:       if (cens[i] == 1 && wav[i]>1)
                   9898:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   9899:       
                   9900:       if (cens[i] == 0 && wav[i]>1)
                   9901:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   9902:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   9903:       
                   9904:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   9905:       if (wav[i] > 1 ) { /* ??? */
                   9906:        LL=LL+A*weight[i];
                   9907:        /*      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]);*/
                   9908:       }
                   9909:     }
                   9910: 
                   9911:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   9912:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   9913:  
                   9914:   return -2*LL*num/sump;
                   9915: }
                   9916: #endif
                   9917: 
1.126     brouard  9918: /******************* Printing html file ***********/
1.201     brouard  9919: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9920:                  int lastpass, int stepm, int weightopt, char model[],\
                   9921:                  int imx,  double p[],double **matcov,double agemortsup){
                   9922:   int i,k;
                   9923: 
                   9924:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   9925:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   9926:   for (i=1;i<=2;i++) 
                   9927:     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  9928:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  9929:   fprintf(fichtm,"</ul>");
                   9930: 
                   9931: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   9932: 
                   9933:  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>");
                   9934: 
                   9935:  for (k=agegomp;k<(agemortsup-2);k++) 
                   9936:    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]);
                   9937: 
                   9938:  
                   9939:   fflush(fichtm);
                   9940: }
                   9941: 
                   9942: /******************* Gnuplot file **************/
1.201     brouard  9943: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  9944: 
                   9945:   char dirfileres[132],optfileres[132];
1.164     brouard  9946: 
1.126     brouard  9947:   int ng;
                   9948: 
                   9949: 
                   9950:   /*#ifdef windows */
                   9951:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   9952:     /*#endif */
                   9953: 
                   9954: 
                   9955:   strcpy(dirfileres,optionfilefiname);
                   9956:   strcpy(optfileres,"vpl");
1.199     brouard  9957:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  9958:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  9959:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  9960:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  9961:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   9962: 
                   9963: } 
                   9964: 
1.136     brouard  9965: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   9966: {
1.126     brouard  9967: 
1.136     brouard  9968:   /*-------- data file ----------*/
                   9969:   FILE *fic;
                   9970:   char dummy[]="                         ";
1.240     brouard  9971:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  9972:   int lstra;
1.136     brouard  9973:   int linei, month, year,iout;
1.302     brouard  9974:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  9975:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  9976:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  9977:   char *stratrunc;
1.223     brouard  9978: 
1.240     brouard  9979:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   9980:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  9981:   for(v=1;v<NCOVMAX;v++){
                   9982:     DummyV[v]=0;
                   9983:     FixedV[v]=0;
                   9984:   }
1.126     brouard  9985: 
1.240     brouard  9986:   for(v=1; v <=ncovcol;v++){
                   9987:     DummyV[v]=0;
                   9988:     FixedV[v]=0;
                   9989:   }
                   9990:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   9991:     DummyV[v]=1;
                   9992:     FixedV[v]=0;
                   9993:   }
                   9994:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   9995:     DummyV[v]=0;
                   9996:     FixedV[v]=1;
                   9997:   }
                   9998:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   9999:     DummyV[v]=1;
                   10000:     FixedV[v]=1;
                   10001:   }
                   10002:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10003:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10004:     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]);
                   10005:   }
1.126     brouard  10006: 
1.136     brouard  10007:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10008:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10009:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10010:   }
1.126     brouard  10011: 
1.302     brouard  10012:     /* Is it a BOM UTF-8 Windows file? */
                   10013:   /* First data line */
                   10014:   linei=0;
                   10015:   while(fgets(line, MAXLINE, fic)) {
                   10016:     noffset=0;
                   10017:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10018:     {
                   10019:       noffset=noffset+3;
                   10020:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10021:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10022:       fflush(ficlog); return 1;
                   10023:     }
                   10024:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10025:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10026:     {
                   10027:       noffset=noffset+2;
1.304     brouard  10028:       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);
                   10029:       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  10030:       fflush(ficlog); return 1;
                   10031:     }
                   10032:     else if( line[0] == 0 && line[1] == 0)
                   10033:     {
                   10034:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10035:        noffset=noffset+4;
1.304     brouard  10036:        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);
                   10037:        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  10038:        fflush(ficlog); return 1;
                   10039:       }
                   10040:     } else{
                   10041:       ;/*printf(" Not a BOM file\n");*/
                   10042:     }
                   10043:         /* If line starts with a # it is a comment */
                   10044:     if (line[noffset] == '#') {
                   10045:       linei=linei+1;
                   10046:       break;
                   10047:     }else{
                   10048:       break;
                   10049:     }
                   10050:   }
                   10051:   fclose(fic);
                   10052:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10053:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10054:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10055:   }
                   10056:   /* Not a Bom file */
                   10057:   
1.136     brouard  10058:   i=1;
                   10059:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10060:     linei=linei+1;
                   10061:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10062:       if(line[j] == '\t')
                   10063:        line[j] = ' ';
                   10064:     }
                   10065:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10066:       ;
                   10067:     };
                   10068:     line[j+1]=0;  /* Trims blanks at end of line */
                   10069:     if(line[0]=='#'){
                   10070:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10071:       printf("Comment line\n%s\n",line);
                   10072:       continue;
                   10073:     }
                   10074:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10075:     strcpy(line, linetmp);
1.223     brouard  10076:     
                   10077:     /* Loops on waves */
                   10078:     for (j=maxwav;j>=1;j--){
                   10079:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10080:        cutv(stra, strb, line, ' '); 
                   10081:        if(strb[0]=='.') { /* Missing value */
                   10082:          lval=-1;
                   10083:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10084:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10085:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10086:            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);
                   10087:            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);
                   10088:            return 1;
                   10089:          }
                   10090:        }else{
                   10091:          errno=0;
                   10092:          /* what_kind_of_number(strb); */
                   10093:          dval=strtod(strb,&endptr); 
                   10094:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10095:          /* if(strb != endptr && *endptr == '\0') */
                   10096:          /*    dval=dlval; */
                   10097:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10098:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10099:            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);
                   10100:            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);
                   10101:            return 1;
                   10102:          }
                   10103:          cotqvar[j][iv][i]=dval; 
                   10104:          cotvar[j][ntv+iv][i]=dval; 
                   10105:        }
                   10106:        strcpy(line,stra);
1.223     brouard  10107:       }/* end loop ntqv */
1.225     brouard  10108:       
1.223     brouard  10109:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10110:        cutv(stra, strb, line, ' '); 
                   10111:        if(strb[0]=='.') { /* Missing value */
                   10112:          lval=-1;
                   10113:        }else{
                   10114:          errno=0;
                   10115:          lval=strtol(strb,&endptr,10); 
                   10116:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10117:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10118:            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);
                   10119:            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);
                   10120:            return 1;
                   10121:          }
                   10122:        }
                   10123:        if(lval <-1 || lval >1){
                   10124:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10125:  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  10126:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10127:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10128:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10129:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10130:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10131:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10132:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10133:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10134:  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  10135:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10136:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10137:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10138:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10139:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10140:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10141:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10142:          return 1;
                   10143:        }
                   10144:        cotvar[j][iv][i]=(double)(lval);
                   10145:        strcpy(line,stra);
1.223     brouard  10146:       }/* end loop ntv */
1.225     brouard  10147:       
1.223     brouard  10148:       /* Statuses  at wave */
1.137     brouard  10149:       cutv(stra, strb, line, ' '); 
1.223     brouard  10150:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10151:        lval=-1;
1.136     brouard  10152:       }else{
1.238     brouard  10153:        errno=0;
                   10154:        lval=strtol(strb,&endptr,10); 
                   10155:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10156:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10157:          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);
                   10158:          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);
                   10159:          return 1;
                   10160:        }
1.136     brouard  10161:       }
1.225     brouard  10162:       
1.136     brouard  10163:       s[j][i]=lval;
1.225     brouard  10164:       
1.223     brouard  10165:       /* Date of Interview */
1.136     brouard  10166:       strcpy(line,stra);
                   10167:       cutv(stra, strb,line,' ');
1.169     brouard  10168:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10169:       }
1.169     brouard  10170:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10171:        month=99;
                   10172:        year=9999;
1.136     brouard  10173:       }else{
1.225     brouard  10174:        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);
                   10175:        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);
                   10176:        return 1;
1.136     brouard  10177:       }
                   10178:       anint[j][i]= (double) year; 
1.302     brouard  10179:       mint[j][i]= (double)month;
                   10180:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10181:       /*       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]); */
                   10182:       /*       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]); */
                   10183:       /* } */
1.136     brouard  10184:       strcpy(line,stra);
1.223     brouard  10185:     } /* End loop on waves */
1.225     brouard  10186:     
1.223     brouard  10187:     /* Date of death */
1.136     brouard  10188:     cutv(stra, strb,line,' '); 
1.169     brouard  10189:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10190:     }
1.169     brouard  10191:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10192:       month=99;
                   10193:       year=9999;
                   10194:     }else{
1.141     brouard  10195:       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  10196:       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);
                   10197:       return 1;
1.136     brouard  10198:     }
                   10199:     andc[i]=(double) year; 
                   10200:     moisdc[i]=(double) month; 
                   10201:     strcpy(line,stra);
                   10202:     
1.223     brouard  10203:     /* Date of birth */
1.136     brouard  10204:     cutv(stra, strb,line,' '); 
1.169     brouard  10205:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10206:     }
1.169     brouard  10207:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10208:       month=99;
                   10209:       year=9999;
                   10210:     }else{
1.141     brouard  10211:       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);
                   10212:       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  10213:       return 1;
1.136     brouard  10214:     }
                   10215:     if (year==9999) {
1.141     brouard  10216:       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);
                   10217:       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  10218:       return 1;
                   10219:       
1.136     brouard  10220:     }
                   10221:     annais[i]=(double)(year);
1.302     brouard  10222:     moisnais[i]=(double)(month);
                   10223:     for (j=1;j<=maxwav;j++){
                   10224:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10225:        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]);
                   10226:        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]);
                   10227:       }
                   10228:     }
                   10229: 
1.136     brouard  10230:     strcpy(line,stra);
1.225     brouard  10231:     
1.223     brouard  10232:     /* Sample weight */
1.136     brouard  10233:     cutv(stra, strb,line,' '); 
                   10234:     errno=0;
                   10235:     dval=strtod(strb,&endptr); 
                   10236:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10237:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10238:       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  10239:       fflush(ficlog);
                   10240:       return 1;
                   10241:     }
                   10242:     weight[i]=dval; 
                   10243:     strcpy(line,stra);
1.225     brouard  10244:     
1.223     brouard  10245:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10246:       cutv(stra, strb, line, ' '); 
                   10247:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10248:        lval=-1;
1.311     brouard  10249:        coqvar[iv][i]=NAN; 
                   10250:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10251:       }else{
1.225     brouard  10252:        errno=0;
                   10253:        /* what_kind_of_number(strb); */
                   10254:        dval=strtod(strb,&endptr);
                   10255:        /* if(strb != endptr && *endptr == '\0') */
                   10256:        /*   dval=dlval; */
                   10257:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10258:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10259:          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);
                   10260:          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);
                   10261:          return 1;
                   10262:        }
                   10263:        coqvar[iv][i]=dval; 
1.226     brouard  10264:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10265:       }
                   10266:       strcpy(line,stra);
                   10267:     }/* end loop nqv */
1.136     brouard  10268:     
1.223     brouard  10269:     /* Covariate values */
1.136     brouard  10270:     for (j=ncovcol;j>=1;j--){
                   10271:       cutv(stra, strb,line,' '); 
1.223     brouard  10272:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10273:        lval=-1;
1.136     brouard  10274:       }else{
1.225     brouard  10275:        errno=0;
                   10276:        lval=strtol(strb,&endptr,10); 
                   10277:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10278:          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);
                   10279:          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);
                   10280:          return 1;
                   10281:        }
1.136     brouard  10282:       }
                   10283:       if(lval <-1 || lval >1){
1.225     brouard  10284:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10285:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10286:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10287:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10288:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10289:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10290:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10291:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10292:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10293:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10294:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10295:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10296:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10297:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10298:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10299:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10300:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10301:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10302:        return 1;
1.136     brouard  10303:       }
                   10304:       covar[j][i]=(double)(lval);
                   10305:       strcpy(line,stra);
                   10306:     }  
                   10307:     lstra=strlen(stra);
1.225     brouard  10308:     
1.136     brouard  10309:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10310:       stratrunc = &(stra[lstra-9]);
                   10311:       num[i]=atol(stratrunc);
                   10312:     }
                   10313:     else
                   10314:       num[i]=atol(stra);
                   10315:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10316:       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;}*/
                   10317:     
                   10318:     i=i+1;
                   10319:   } /* End loop reading  data */
1.225     brouard  10320:   
1.136     brouard  10321:   *imax=i-1; /* Number of individuals */
                   10322:   fclose(fic);
1.225     brouard  10323:   
1.136     brouard  10324:   return (0);
1.164     brouard  10325:   /* endread: */
1.225     brouard  10326:   printf("Exiting readdata: ");
                   10327:   fclose(fic);
                   10328:   return (1);
1.223     brouard  10329: }
1.126     brouard  10330: 
1.234     brouard  10331: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10332:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10333:   while (*p2 == ' ')
1.234     brouard  10334:     p2++; 
                   10335:   /* while ((*p1++ = *p2++) !=0) */
                   10336:   /*   ; */
                   10337:   /* do */
                   10338:   /*   while (*p2 == ' ') */
                   10339:   /*     p2++; */
                   10340:   /* while (*p1++ == *p2++); */
                   10341:   *stri=p2; 
1.145     brouard  10342: }
                   10343: 
1.330     brouard  10344: int decoderesult( char resultline[], int nres)
1.230     brouard  10345: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10346: {
1.235     brouard  10347:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10348:   char resultsav[MAXLINE];
1.330     brouard  10349:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10350:   /* int modelresult[MAXLINE]; */
1.230     brouard  10351:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10352: 
1.234     brouard  10353:   removefirstspace(&resultline);
1.332     brouard  10354:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10355: 
1.332     brouard  10356:   strcpy(resultsav,resultline);
                   10357:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10358:   if (strlen(resultsav) >1){
1.334     brouard  10359:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10360:   }
1.253     brouard  10361:   if(j == 0){ /* Resultline but no = */
                   10362:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10363:     return (0);
                   10364:   }
1.234     brouard  10365:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10366:     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);
                   10367:     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  10368:     /* return 1;*/
1.234     brouard  10369:   }
1.334     brouard  10370:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10371:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10372:       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  10373:       /* 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  10374:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10375:       /* If a blank, then strc="V4=" and strd='\0' */
                   10376:       if(strc[0]=='\0'){
                   10377:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10378:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10379:        return 1;
                   10380:       }
1.234     brouard  10381:     }else
                   10382:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10383:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10384:     
1.230     brouard  10385:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10386:     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  10387:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10388:     /* cptcovsel++;     */
                   10389:     if (nbocc(stra,'=') >0)
                   10390:       strcpy(resultsav,stra); /* and analyzes it */
                   10391:   }
1.235     brouard  10392:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10393:   /* 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  10394:   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  10395:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10396:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10397:       match=0;
1.318     brouard  10398:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10399:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10400:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10401:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10402:          break;
                   10403:        }
                   10404:       }
                   10405:       if(match == 0){
1.332     brouard  10406:        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]);
                   10407:        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  10408:        return 1;
1.234     brouard  10409:       }
1.332     brouard  10410:     }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*/
                   10411:       /* We feed resultmodel[k1]=k2; */
                   10412:       match=0;
                   10413:       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 */
                   10414:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10415:          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  10416:          resultmodel[nres][k1]=k2; /* Added here */
                   10417:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10418:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10419:          break;
                   10420:        }
                   10421:       }
                   10422:       if(match == 0){
                   10423:        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  10424:        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  10425:       return 1;
                   10426:       }
                   10427:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10428:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10429:       match=0;
                   10430:       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]);
                   10431:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10432:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10433:          /* modelresult[k2]=k1; */
                   10434:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10435:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10436:        }
                   10437:       }
                   10438:       if(match == 0){
                   10439:        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  10440:        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  10441:        return 1;
                   10442:       }
                   10443:       match=0;
                   10444:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10445:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10446:          /* modelresult[k2]=k1;*/
                   10447:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10448:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10449:          break;
                   10450:        }
                   10451:       }
                   10452:       if(match == 0){
                   10453:        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  10454:        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  10455:        return 1;
                   10456:       }
                   10457:     }/* End of testing */
1.333     brouard  10458:   }/* End loop cptcovt */
1.235     brouard  10459:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10460:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10461:   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)
                   10462:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10463:     match=0;
1.318     brouard  10464:     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  10465:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10466:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10467:          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  10468:          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  10469:          ++match;
                   10470:        }
                   10471:       }
                   10472:     }
                   10473:     if(match == 0){
1.332     brouard  10474:       printf("Error in result line: variable V%d is missing in model; result: %s, model=%s\n",Tvarsel[k2], resultline, model);
                   10475:       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  10476:       return 1;
1.234     brouard  10477:     }else if(match > 1){
                   10478:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
1.310     brouard  10479:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   10480:       return 1;
1.234     brouard  10481:     }
                   10482:   }
1.334     brouard  10483:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10484:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10485:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10486:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10487:   /* 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*/
                   10488:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10489:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10490:   /*    1 0 0 0 */
                   10491:   /*    2 1 0 0 */
                   10492:   /*    3 0 1 0 */ 
1.330     brouard  10493:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10494:   /*    5 0 0 1 */
1.330     brouard  10495:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10496:   /*    7 0 1 1 */
                   10497:   /*    8 1 1 1 */
1.237     brouard  10498:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10499:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10500:   /* V5*age V5 known which value for nres?  */
                   10501:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10502:   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.
                   10503:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10504:     /* k counting number of combination of single dummies in the equation model */
                   10505:     /* k4 counting single dummies in the equation model */
                   10506:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10507:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10508:        /* 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  10509:       /* 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  10510:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10511:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10512:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10513:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10514:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10515:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10516:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10517:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10518:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10519:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10520:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10521:       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  10522:       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  10523:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10524:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10525:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10526:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10527:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10528:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10529:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10530:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10531:       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  10532:       k4++;;
1.331     brouard  10533:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10534:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10535:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10536:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10537:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10538:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10539:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10540:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10541:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10542:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10543:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10544:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10545:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10546:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10547:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10548:       precov[nres][k1]=Tvalsel[k3q];
                   10549:       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  10550:       k4q++;;
1.331     brouard  10551:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10552:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10553:       /* Wrong we want the value of variable name Tvar[k1] */
                   10554:       
                   10555:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10556:       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  10557:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10558:       precov[nres][k1]=Tvalsel[k3];
                   10559:       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  10560:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10561:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10562:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10563:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10564:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10565:       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  10566:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10567:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10568:       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  10569:     }else{
1.332     brouard  10570:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10571:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10572:     }
                   10573:   }
1.234     brouard  10574:   
1.334     brouard  10575:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10576:   return (0);
                   10577: }
1.235     brouard  10578: 
1.230     brouard  10579: int decodemodel( char model[], int lastobs)
                   10580:  /**< This routine decodes the model and returns:
1.224     brouard  10581:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10582:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10583:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10584:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10585:        * - cptcovage number of covariates with age*products =2
                   10586:        * - cptcovs number of simple covariates
                   10587:        * - 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
                   10588:        *     which is a new column after the 9 (ncovcol) variables. 
1.319     brouard  10589:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10590:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10591:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10592:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10593:        */
1.319     brouard  10594: /* 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  10595: {
1.238     brouard  10596:   int i, j, k, ks, v;
1.227     brouard  10597:   int  j1, k1, k2, k3, k4;
1.136     brouard  10598:   char modelsav[80];
1.145     brouard  10599:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10600:   char *strpt;
1.136     brouard  10601: 
1.145     brouard  10602:   /*removespace(model);*/
1.136     brouard  10603:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10604:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10605:     if (strstr(model,"AGE") !=0){
1.192     brouard  10606:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10607:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10608:       return 1;
                   10609:     }
1.141     brouard  10610:     if (strstr(model,"v") !=0){
                   10611:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   10612:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   10613:       return 1;
                   10614:     }
1.187     brouard  10615:     strcpy(modelsav,model); 
                   10616:     if ((strpt=strstr(model,"age*age")) !=0){
                   10617:       printf(" strpt=%s, model=%s\n",strpt, model);
                   10618:       if(strpt != model){
1.234     brouard  10619:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10620:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10621:  corresponding column of parameters.\n",model);
1.234     brouard  10622:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10623:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10624:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10625:        return 1;
1.225     brouard  10626:       }
1.187     brouard  10627:       nagesqr=1;
                   10628:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10629:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10630:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10631:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10632:       else 
1.234     brouard  10633:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10634:     }else
                   10635:       nagesqr=0;
                   10636:     if (strlen(modelsav) >1){
                   10637:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10638:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10639:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10640:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10641:                     * cst, age and age*age 
                   10642:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10643:       /* including age products which are counted in cptcovage.
                   10644:        * but the covariates which are products must be treated 
                   10645:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10646:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10647:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10648:       
                   10649:       
1.187     brouard  10650:       /*   Design
                   10651:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10652:        *  <          ncovcol=8                >
                   10653:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10654:        *   k=  1    2      3       4     5       6      7        8
                   10655:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10656:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10657:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10658:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10659:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10660:        *  Tage[++cptcovage]=k
                   10661:        *       if products, new covar are created after ncovcol with k1
                   10662:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10663:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10664:        *  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
                   10665:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10666:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10667:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10668:        *  <          ncovcol=8                >
                   10669:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10670:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10671:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10672:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10673:        * p Tprod[1]@2={                         6, 5}
                   10674:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10675:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10676:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10677:        *How to reorganize? Tvars(orted)
1.187     brouard  10678:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10679:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10680:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10681:        * Struct []
                   10682:        */
1.225     brouard  10683:       
1.187     brouard  10684:       /* This loop fills the array Tvar from the string 'model'.*/
                   10685:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10686:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10687:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10688:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10689:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10690:       /*       k=1 Tvar[1]=2 (from V2) */
                   10691:       /*       k=5 Tvar[5] */
                   10692:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10693:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10694:       /*       } */
1.198     brouard  10695:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10696:       /*
                   10697:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10698:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10699:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10700:       }
1.187     brouard  10701:       cptcovage=0;
1.319     brouard  10702:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10703:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10704:                                         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" */
                   10705:        if (nbocc(modelsav,'+')==0)
                   10706:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10707:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10708:        /*scanf("%d",i);*/
1.319     brouard  10709:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10710:          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  10711:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10712:            /* covar is not filled and then is empty */
                   10713:            cptcovprod--;
                   10714:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10715:            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  10716:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10717:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10718:            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  10719:            /*printf("stre=%s ", stre);*/
                   10720:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10721:            cptcovprod--;
                   10722:            cutl(stre,strb,strc,'V');
                   10723:            Tvar[k]=atoi(stre);
                   10724:            Typevar[k]=1;  /* 1 for age product */
                   10725:            cptcovage++;
                   10726:            Tage[cptcovage]=k;
                   10727:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10728:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10729:            cptcovn++;
                   10730:            cptcovprodnoage++;k1++;
                   10731:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   10732:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   10733:                                                because this model-covariate is a construction we invent a new column
                   10734:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335   ! brouard  10735:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  10736:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   10737:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=4 etc */
1.335   ! brouard  10738:            /* Please remark that the new variables are model dependent */
        !          10739:            /* If we have 4 variable but the model uses only 3, like in
        !          10740:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
        !          10741:             *  k=     1     2       3   4     5        6        7       8
        !          10742:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
        !          10743:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
        !          10744:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
        !          10745:             */
1.234     brouard  10746:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   10747:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10748:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10749:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10750:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10751:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10752:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10753:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10754:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10755:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10756:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10757:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10758:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   10759:            for (i=1; i<=lastobs;i++){
                   10760:              /* Computes the new covariate which is a product of
                   10761:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   10762:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   10763:            }
                   10764:          } /* End age is not in the model */
                   10765:        } /* End if model includes a product */
1.319     brouard  10766:        else { /* not a product */
1.234     brouard  10767:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   10768:          /*  scanf("%d",i);*/
                   10769:          cutl(strd,strc,strb,'V');
                   10770:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   10771:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   10772:          Tvar[k]=atoi(strd);
                   10773:          Typevar[k]=0;  /* 0 for simple covariates */
                   10774:        }
                   10775:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  10776:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  10777:                                  scanf("%d",i);*/
1.187     brouard  10778:       } /* end of loop + on total covariates */
                   10779:     } /* end if strlen(modelsave == 0) age*age might exist */
                   10780:   } /* end if strlen(model == 0) */
1.136     brouard  10781:   
                   10782:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   10783:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  10784:   
1.136     brouard  10785:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  10786:      printf("cptcovprod=%d ", cptcovprod);
                   10787:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   10788:      scanf("%d ",i);*/
                   10789: 
                   10790: 
1.230     brouard  10791: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   10792:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  10793: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   10794:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   10795:    k =           1    2   3     4       5       6      7      8        9
                   10796:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  10797:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  10798:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   10799:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   10800:          Tmodelind[combination of covar]=k;
1.225     brouard  10801: */  
                   10802: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  10803:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  10804:   /* 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  10805:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  10806:   printf("Model=1+age+%s\n\
1.227     brouard  10807: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10808: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10809: 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  10810:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  10811: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   10812: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   10813: 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  10814:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  10815:   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 */
                   10816:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  10817:       Fixed[k]= 0;
                   10818:       Dummy[k]= 0;
1.225     brouard  10819:       ncoveff++;
1.232     brouard  10820:       ncovf++;
1.234     brouard  10821:       nsd++;
                   10822:       modell[k].maintype= FTYPE;
                   10823:       TvarsD[nsd]=Tvar[k];
                   10824:       TvarsDind[nsd]=k;
1.330     brouard  10825:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  10826:       TvarF[ncovf]=Tvar[k];
                   10827:       TvarFind[ncovf]=k;
                   10828:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10829:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   10830:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   10831:       Fixed[k]= 0;
                   10832:       Dummy[k]= 0;
                   10833:       ncoveff++;
                   10834:       ncovf++;
                   10835:       modell[k].maintype= FTYPE;
                   10836:       TvarF[ncovf]=Tvar[k];
1.330     brouard  10837:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  10838:       TvarFind[ncovf]=k;
1.230     brouard  10839:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  10840:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  10841:     }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  10842:       Fixed[k]= 0;
                   10843:       Dummy[k]= 1;
1.230     brouard  10844:       nqfveff++;
1.234     brouard  10845:       modell[k].maintype= FTYPE;
                   10846:       modell[k].subtype= FQ;
                   10847:       nsq++;
1.334     brouard  10848:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   10849:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  10850:       ncovf++;
1.234     brouard  10851:       TvarF[ncovf]=Tvar[k];
                   10852:       TvarFind[ncovf]=k;
1.231     brouard  10853:       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  10854:       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  10855:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  10856:       Fixed[k]= 1;
                   10857:       Dummy[k]= 0;
1.225     brouard  10858:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  10859:       modell[k].maintype= VTYPE;
                   10860:       modell[k].subtype= VD;
                   10861:       nsd++;
                   10862:       TvarsD[nsd]=Tvar[k];
                   10863:       TvarsDind[nsd]=k;
1.330     brouard  10864:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  10865:       ncovv++; /* Only simple time varying variables */
                   10866:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10867:       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  10868:       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 */
                   10869:       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  10870:       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);
                   10871:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  10872:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  10873:       Fixed[k]= 1;
                   10874:       Dummy[k]= 1;
                   10875:       nqtveff++;
                   10876:       modell[k].maintype= VTYPE;
                   10877:       modell[k].subtype= VQ;
                   10878:       ncovv++; /* Only simple time varying variables */
                   10879:       nsq++;
1.334     brouard  10880:       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) */
                   10881:       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  10882:       TvarV[ncovv]=Tvar[k];
1.242     brouard  10883:       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  10884:       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 */
                   10885:       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  10886:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   10887:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   10888:       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  10889:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  10890:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  10891:       ncova++;
                   10892:       TvarA[ncova]=Tvar[k];
                   10893:       TvarAind[ncova]=k;
1.231     brouard  10894:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  10895:        Fixed[k]= 2;
                   10896:        Dummy[k]= 2;
                   10897:        modell[k].maintype= ATYPE;
                   10898:        modell[k].subtype= APFD;
                   10899:        /* ncoveff++; */
1.227     brouard  10900:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  10901:        Fixed[k]= 2;
                   10902:        Dummy[k]= 3;
                   10903:        modell[k].maintype= ATYPE;
                   10904:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   10905:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  10906:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  10907:        Fixed[k]= 3;
                   10908:        Dummy[k]= 2;
                   10909:        modell[k].maintype= ATYPE;
                   10910:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   10911:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  10912:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  10913:        Fixed[k]= 3;
                   10914:        Dummy[k]= 3;
                   10915:        modell[k].maintype= ATYPE;
                   10916:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   10917:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  10918:       }
                   10919:     }else if (Typevar[k] == 2) {  /* product without age */
                   10920:       k1=Tposprod[k];
                   10921:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  10922:        if(Tvard[k1][2] <=ncovcol){
                   10923:          Fixed[k]= 1;
                   10924:          Dummy[k]= 0;
                   10925:          modell[k].maintype= FTYPE;
                   10926:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   10927:          ncovf++; /* Fixed variables without age */
                   10928:          TvarF[ncovf]=Tvar[k];
                   10929:          TvarFind[ncovf]=k;
                   10930:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10931:          Fixed[k]= 0;  /* or 2 ?*/
                   10932:          Dummy[k]= 1;
                   10933:          modell[k].maintype= FTYPE;
                   10934:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   10935:          ncovf++; /* Varying variables without age */
                   10936:          TvarF[ncovf]=Tvar[k];
                   10937:          TvarFind[ncovf]=k;
                   10938:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10939:          Fixed[k]= 1;
                   10940:          Dummy[k]= 0;
                   10941:          modell[k].maintype= VTYPE;
                   10942:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   10943:          ncovv++; /* Varying variables without age */
                   10944:          TvarV[ncovv]=Tvar[k];
                   10945:          TvarVind[ncovv]=k;
                   10946:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10947:          Fixed[k]= 1;
                   10948:          Dummy[k]= 1;
                   10949:          modell[k].maintype= VTYPE;
                   10950:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   10951:          ncovv++; /* Varying variables without age */
                   10952:          TvarV[ncovv]=Tvar[k];
                   10953:          TvarVind[ncovv]=k;
                   10954:        }
1.227     brouard  10955:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  10956:        if(Tvard[k1][2] <=ncovcol){
                   10957:          Fixed[k]= 0;  /* or 2 ?*/
                   10958:          Dummy[k]= 1;
                   10959:          modell[k].maintype= FTYPE;
                   10960:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   10961:          ncovf++; /* Fixed variables without age */
                   10962:          TvarF[ncovf]=Tvar[k];
                   10963:          TvarFind[ncovf]=k;
                   10964:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   10965:          Fixed[k]= 1;
                   10966:          Dummy[k]= 1;
                   10967:          modell[k].maintype= VTYPE;
                   10968:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   10969:          ncovv++; /* Varying variables without age */
                   10970:          TvarV[ncovv]=Tvar[k];
                   10971:          TvarVind[ncovv]=k;
                   10972:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   10973:          Fixed[k]= 1;
                   10974:          Dummy[k]= 1;
                   10975:          modell[k].maintype= VTYPE;
                   10976:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   10977:          ncovv++; /* Varying variables without age */
                   10978:          TvarV[ncovv]=Tvar[k];
                   10979:          TvarVind[ncovv]=k;
                   10980:          ncovv++; /* Varying variables without age */
                   10981:          TvarV[ncovv]=Tvar[k];
                   10982:          TvarVind[ncovv]=k;
                   10983:        }
1.227     brouard  10984:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  10985:        if(Tvard[k1][2] <=ncovcol){
                   10986:          Fixed[k]= 1;
                   10987:          Dummy[k]= 1;
                   10988:          modell[k].maintype= VTYPE;
                   10989:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   10990:          ncovv++; /* Varying variables without age */
                   10991:          TvarV[ncovv]=Tvar[k];
                   10992:          TvarVind[ncovv]=k;
                   10993:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   10994:          Fixed[k]= 1;
                   10995:          Dummy[k]= 1;
                   10996:          modell[k].maintype= VTYPE;
                   10997:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   10998:          ncovv++; /* Varying variables without age */
                   10999:          TvarV[ncovv]=Tvar[k];
                   11000:          TvarVind[ncovv]=k;
                   11001:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11002:          Fixed[k]= 1;
                   11003:          Dummy[k]= 0;
                   11004:          modell[k].maintype= VTYPE;
                   11005:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11006:          ncovv++; /* Varying variables without age */
                   11007:          TvarV[ncovv]=Tvar[k];
                   11008:          TvarVind[ncovv]=k;
                   11009:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11010:          Fixed[k]= 1;
                   11011:          Dummy[k]= 1;
                   11012:          modell[k].maintype= VTYPE;
                   11013:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11014:          ncovv++; /* Varying variables without age */
                   11015:          TvarV[ncovv]=Tvar[k];
                   11016:          TvarVind[ncovv]=k;
                   11017:        }
1.227     brouard  11018:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11019:        if(Tvard[k1][2] <=ncovcol){
                   11020:          Fixed[k]= 1;
                   11021:          Dummy[k]= 1;
                   11022:          modell[k].maintype= VTYPE;
                   11023:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11024:          ncovv++; /* Varying variables without age */
                   11025:          TvarV[ncovv]=Tvar[k];
                   11026:          TvarVind[ncovv]=k;
                   11027:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11028:          Fixed[k]= 1;
                   11029:          Dummy[k]= 1;
                   11030:          modell[k].maintype= VTYPE;
                   11031:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11032:          ncovv++; /* Varying variables without age */
                   11033:          TvarV[ncovv]=Tvar[k];
                   11034:          TvarVind[ncovv]=k;
                   11035:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11036:          Fixed[k]= 1;
                   11037:          Dummy[k]= 1;
                   11038:          modell[k].maintype= VTYPE;
                   11039:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11040:          ncovv++; /* Varying variables without age */
                   11041:          TvarV[ncovv]=Tvar[k];
                   11042:          TvarVind[ncovv]=k;
                   11043:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11044:          Fixed[k]= 1;
                   11045:          Dummy[k]= 1;
                   11046:          modell[k].maintype= VTYPE;
                   11047:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11048:          ncovv++; /* Varying variables without age */
                   11049:          TvarV[ncovv]=Tvar[k];
                   11050:          TvarVind[ncovv]=k;
                   11051:        }
1.227     brouard  11052:       }else{
1.240     brouard  11053:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11054:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11055:       } /*end k1*/
1.225     brouard  11056:     }else{
1.226     brouard  11057:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11058:       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  11059:     }
1.227     brouard  11060:     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  11061:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11062:     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]);
                   11063:   }
                   11064:   /* Searching for doublons in the model */
                   11065:   for(k1=1; k1<= cptcovt;k1++){
                   11066:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11067:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11068:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11069:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11070:          if(Tvar[k1]==Tvar[k2]){
1.285     brouard  11071:            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]);
                   11072:            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  11073:            return(1);
                   11074:          }
                   11075:        }else if (Typevar[k1] ==2){
                   11076:          k3=Tposprod[k1];
                   11077:          k4=Tposprod[k2];
                   11078:          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])) ){
                   11079:            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]]);
                   11080:            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);
                   11081:            return(1);
                   11082:          }
                   11083:        }
1.227     brouard  11084:       }
                   11085:     }
1.225     brouard  11086:   }
                   11087:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11088:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11089:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11090:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11091:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11092:   /*endread:*/
1.225     brouard  11093:   printf("Exiting decodemodel: ");
                   11094:   return (1);
1.136     brouard  11095: }
                   11096: 
1.169     brouard  11097: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11098: {/* Check ages at death */
1.136     brouard  11099:   int i, m;
1.218     brouard  11100:   int firstone=0;
                   11101:   
1.136     brouard  11102:   for (i=1; i<=imx; i++) {
                   11103:     for(m=2; (m<= maxwav); m++) {
                   11104:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11105:        anint[m][i]=9999;
1.216     brouard  11106:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11107:          s[m][i]=-1;
1.136     brouard  11108:       }
                   11109:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11110:        *nberr = *nberr + 1;
1.218     brouard  11111:        if(firstone == 0){
                   11112:          firstone=1;
1.260     brouard  11113:        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  11114:        }
1.262     brouard  11115:        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  11116:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11117:       }
                   11118:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11119:        (*nberr)++;
1.259     brouard  11120:        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  11121:        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  11122:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11123:       }
                   11124:     }
                   11125:   }
                   11126: 
                   11127:   for (i=1; i<=imx; i++)  {
                   11128:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11129:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11130:       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  11131:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11132:          if(agedc[i]>0){
                   11133:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11134:              agev[m][i]=agedc[i];
1.214     brouard  11135:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11136:            }else {
1.136     brouard  11137:              if ((int)andc[i]!=9999){
                   11138:                nbwarn++;
                   11139:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11140:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11141:                agev[m][i]=-1;
                   11142:              }
                   11143:            }
1.169     brouard  11144:          } /* agedc > 0 */
1.214     brouard  11145:        } /* end if */
1.136     brouard  11146:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11147:                                 years but with the precision of a month */
                   11148:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11149:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11150:            agev[m][i]=1;
                   11151:          else if(agev[m][i] < *agemin){ 
                   11152:            *agemin=agev[m][i];
                   11153:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11154:          }
                   11155:          else if(agev[m][i] >*agemax){
                   11156:            *agemax=agev[m][i];
1.156     brouard  11157:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11158:          }
                   11159:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11160:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11161:        } /* en if 9*/
1.136     brouard  11162:        else { /* =9 */
1.214     brouard  11163:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11164:          agev[m][i]=1;
                   11165:          s[m][i]=-1;
                   11166:        }
                   11167:       }
1.214     brouard  11168:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11169:        agev[m][i]=1;
1.214     brouard  11170:       else{
                   11171:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11172:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11173:        agev[m][i]=0;
                   11174:       }
                   11175:     } /* End for lastpass */
                   11176:   }
1.136     brouard  11177:     
                   11178:   for (i=1; i<=imx; i++)  {
                   11179:     for(m=firstpass; (m<=lastpass); m++){
                   11180:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11181:        (*nberr)++;
1.136     brouard  11182:        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);     
                   11183:        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);     
                   11184:        return 1;
                   11185:       }
                   11186:     }
                   11187:   }
                   11188: 
                   11189:   /*for (i=1; i<=imx; i++){
                   11190:   for (m=firstpass; (m<lastpass); m++){
                   11191:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11192: }
                   11193: 
                   11194: }*/
                   11195: 
                   11196: 
1.139     brouard  11197:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11198:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11199: 
                   11200:   return (0);
1.164     brouard  11201:  /* endread:*/
1.136     brouard  11202:     printf("Exiting calandcheckages: ");
                   11203:     return (1);
                   11204: }
                   11205: 
1.172     brouard  11206: #if defined(_MSC_VER)
                   11207: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11208: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11209: //#include "stdafx.h"
                   11210: //#include <stdio.h>
                   11211: //#include <tchar.h>
                   11212: //#include <windows.h>
                   11213: //#include <iostream>
                   11214: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11215: 
                   11216: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11217: 
                   11218: BOOL IsWow64()
                   11219: {
                   11220:        BOOL bIsWow64 = FALSE;
                   11221: 
                   11222:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11223:        //  (HANDLE, PBOOL);
                   11224: 
                   11225:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11226: 
                   11227:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11228:        const char funcName[] = "IsWow64Process";
                   11229:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11230:                GetProcAddress(module, funcName);
                   11231: 
                   11232:        if (NULL != fnIsWow64Process)
                   11233:        {
                   11234:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11235:                        &bIsWow64))
                   11236:                        //throw std::exception("Unknown error");
                   11237:                        printf("Unknown error\n");
                   11238:        }
                   11239:        return bIsWow64 != FALSE;
                   11240: }
                   11241: #endif
1.177     brouard  11242: 
1.191     brouard  11243: void syscompilerinfo(int logged)
1.292     brouard  11244: {
                   11245: #include <stdint.h>
                   11246: 
                   11247:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11248:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11249:    /* /GS /W3 /Gy
                   11250:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11251:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11252:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11253:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11254:    */ 
                   11255:    /* 64 bits */
1.185     brouard  11256:    /*
                   11257:      /GS /W3 /Gy
                   11258:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11259:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11260:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11261:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11262:    /* Optimization are useless and O3 is slower than O2 */
                   11263:    /*
                   11264:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11265:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11266:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11267:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11268:    */
1.186     brouard  11269:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11270:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11271:       /PDB:"visual studio
                   11272:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11273:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11274:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11275:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11276:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11277:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11278:       uiAccess='false'"
                   11279:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11280:       /NOLOGO /TLBID:1
                   11281:    */
1.292     brouard  11282: 
                   11283: 
1.177     brouard  11284: #if defined __INTEL_COMPILER
1.178     brouard  11285: #if defined(__GNUC__)
                   11286:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11287: #endif
1.177     brouard  11288: #elif defined(__GNUC__) 
1.179     brouard  11289: #ifndef  __APPLE__
1.174     brouard  11290: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11291: #endif
1.177     brouard  11292:    struct utsname sysInfo;
1.178     brouard  11293:    int cross = CROSS;
                   11294:    if (cross){
                   11295:           printf("Cross-");
1.191     brouard  11296:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11297:    }
1.174     brouard  11298: #endif
                   11299: 
1.191     brouard  11300:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11301: #if defined(__clang__)
1.191     brouard  11302:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11303: #endif
                   11304: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11305:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11306: #endif
                   11307: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11308:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11309: #endif
                   11310: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11311:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11312: #endif
                   11313: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11314:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11315: #endif
                   11316: #if defined(_MSC_VER)
1.191     brouard  11317:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11318: #endif
                   11319: #if defined(__PGI)
1.191     brouard  11320:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11321: #endif
                   11322: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11323:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11324: #endif
1.191     brouard  11325:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11326:    
1.167     brouard  11327: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11328: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11329:     // Windows (x64 and x86)
1.191     brouard  11330:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11331: #elif __unix__ // all unices, not all compilers
                   11332:     // Unix
1.191     brouard  11333:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11334: #elif __linux__
                   11335:     // linux
1.191     brouard  11336:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11337: #elif __APPLE__
1.174     brouard  11338:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11339:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11340: #endif
                   11341: 
                   11342: /*  __MINGW32__          */
                   11343: /*  __CYGWIN__  */
                   11344: /* __MINGW64__  */
                   11345: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11346: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11347: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11348: /* _WIN64  // Defined for applications for Win64. */
                   11349: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11350: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11351: 
1.167     brouard  11352: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11353:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11354: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11355:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11356: #else
1.191     brouard  11357:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11358: #endif
                   11359: 
1.169     brouard  11360: #if defined(__GNUC__)
                   11361: # if defined(__GNUC_PATCHLEVEL__)
                   11362: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11363:                             + __GNUC_MINOR__ * 100 \
                   11364:                             + __GNUC_PATCHLEVEL__)
                   11365: # else
                   11366: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11367:                             + __GNUC_MINOR__ * 100)
                   11368: # endif
1.174     brouard  11369:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11370:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11371: 
                   11372:    if (uname(&sysInfo) != -1) {
                   11373:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11374:         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  11375:    }
                   11376:    else
                   11377:       perror("uname() error");
1.179     brouard  11378:    //#ifndef __INTEL_COMPILER 
                   11379: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11380:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11381:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11382: #endif
1.169     brouard  11383: #endif
1.172     brouard  11384: 
1.286     brouard  11385:    //   void main ()
1.172     brouard  11386:    //   {
1.169     brouard  11387: #if defined(_MSC_VER)
1.174     brouard  11388:    if (IsWow64()){
1.191     brouard  11389:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11390:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11391:    }
                   11392:    else{
1.191     brouard  11393:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11394:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11395:    }
1.172     brouard  11396:    //     printf("\nPress Enter to continue...");
                   11397:    //     getchar();
                   11398:    //   }
                   11399: 
1.169     brouard  11400: #endif
                   11401:    
1.167     brouard  11402: 
1.219     brouard  11403: }
1.136     brouard  11404: 
1.219     brouard  11405: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11406:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11407:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11408:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11409:   /* double ftolpl = 1.e-10; */
1.180     brouard  11410:   double age, agebase, agelim;
1.203     brouard  11411:   double tot;
1.180     brouard  11412: 
1.202     brouard  11413:   strcpy(filerespl,"PL_");
                   11414:   strcat(filerespl,fileresu);
                   11415:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11416:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11417:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11418:   }
1.288     brouard  11419:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11420:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11421:   pstamp(ficrespl);
1.288     brouard  11422:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11423:   fprintf(ficrespl,"#Age ");
                   11424:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11425:   fprintf(ficrespl,"\n");
1.180     brouard  11426:   
1.219     brouard  11427:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11428: 
1.219     brouard  11429:   agebase=ageminpar;
                   11430:   agelim=agemaxpar;
1.180     brouard  11431: 
1.227     brouard  11432:   /* i1=pow(2,ncoveff); */
1.234     brouard  11433:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11434:   if (cptcovn < 1){i1=1;}
1.180     brouard  11435: 
1.238     brouard  11436:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   11437:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  11438:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11439:        continue;
1.235     brouard  11440: 
1.238     brouard  11441:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11442:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11443:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11444:       /* k=k+1; */
                   11445:       /* to clean */
1.332     brouard  11446:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11447:       fprintf(ficrespl,"#******");
                   11448:       printf("#******");
                   11449:       fprintf(ficlog,"#******");
                   11450:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11451:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   11452:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* Here problem for varying dummy*/
                   11453:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11454:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11455:       }
                   11456:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11457:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11458:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11459:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11460:       }
                   11461:       fprintf(ficrespl,"******\n");
                   11462:       printf("******\n");
                   11463:       fprintf(ficlog,"******\n");
                   11464:       if(invalidvarcomb[k]){
                   11465:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11466:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11467:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11468:        continue;
                   11469:       }
1.219     brouard  11470: 
1.238     brouard  11471:       fprintf(ficrespl,"#Age ");
                   11472:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11473:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11474:       }
                   11475:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11476:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11477:     
1.238     brouard  11478:       for (age=agebase; age<=agelim; age++){
                   11479:        /* for (age=agebase; age<=agebase; age++){ */
                   11480:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   11481:        fprintf(ficrespl,"%.0f ",age );
                   11482:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11483:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11484:        tot=0.;
                   11485:        for(i=1; i<=nlstate;i++){
                   11486:          tot +=  prlim[i][i];
                   11487:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11488:        }
                   11489:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11490:       } /* Age */
                   11491:       /* was end of cptcod */
                   11492:     } /* cptcov */
                   11493:   } /* nres */
1.219     brouard  11494:   return 0;
1.180     brouard  11495: }
                   11496: 
1.218     brouard  11497: 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  11498:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11499:        
                   11500:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11501:    * at any age between ageminpar and agemaxpar
                   11502:         */
1.235     brouard  11503:   int i, j, k, i1, nres=0 ;
1.217     brouard  11504:   /* double ftolpl = 1.e-10; */
                   11505:   double age, agebase, agelim;
                   11506:   double tot;
1.218     brouard  11507:   /* double ***mobaverage; */
                   11508:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11509: 
                   11510:   strcpy(fileresplb,"PLB_");
                   11511:   strcat(fileresplb,fileresu);
                   11512:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11513:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11514:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11515:   }
1.288     brouard  11516:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11517:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11518:   pstamp(ficresplb);
1.288     brouard  11519:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11520:   fprintf(ficresplb,"#Age ");
                   11521:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11522:   fprintf(ficresplb,"\n");
                   11523:   
1.218     brouard  11524:   
                   11525:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11526:   
                   11527:   agebase=ageminpar;
                   11528:   agelim=agemaxpar;
                   11529:   
                   11530:   
1.227     brouard  11531:   i1=pow(2,cptcoveff);
1.218     brouard  11532:   if (cptcovn < 1){i1=1;}
1.227     brouard  11533:   
1.238     brouard  11534:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11535:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11536:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11537:        continue;
1.332     brouard  11538:      /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11539:       fprintf(ficresplb,"#******");
                   11540:       printf("#******");
                   11541:       fprintf(ficlog,"#******");
                   11542:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.332     brouard  11543:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11544:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   11545:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11546:       }
                   11547:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11548:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11549:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
                   11550:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11551:       }
                   11552:       fprintf(ficresplb,"******\n");
                   11553:       printf("******\n");
                   11554:       fprintf(ficlog,"******\n");
                   11555:       if(invalidvarcomb[k]){
                   11556:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11557:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11558:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11559:        continue;
                   11560:       }
1.218     brouard  11561:     
1.238     brouard  11562:       fprintf(ficresplb,"#Age ");
                   11563:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  11564:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11565:       }
                   11566:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11567:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11568:     
                   11569:     
1.238     brouard  11570:       for (age=agebase; age<=agelim; age++){
                   11571:        /* for (age=agebase; age<=agebase; age++){ */
                   11572:        if(mobilavproj > 0){
                   11573:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11574:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11575:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11576:        }else if (mobilavproj == 0){
                   11577:          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);
                   11578:          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);
                   11579:          exit(1);
                   11580:        }else{
                   11581:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11582:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11583:          /* printf("TOTOT\n"); */
                   11584:           /* exit(1); */
1.238     brouard  11585:        }
                   11586:        fprintf(ficresplb,"%.0f ",age );
                   11587:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  11588:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11589:        tot=0.;
                   11590:        for(i=1; i<=nlstate;i++){
                   11591:          tot +=  bprlim[i][i];
                   11592:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11593:        }
                   11594:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11595:       } /* Age */
                   11596:       /* was end of cptcod */
1.255     brouard  11597:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  11598:     } /* end of any combination */
                   11599:   } /* end of nres */  
1.218     brouard  11600:   /* hBijx(p, bage, fage); */
                   11601:   /* fclose(ficrespijb); */
                   11602:   
                   11603:   return 0;
1.217     brouard  11604: }
1.218     brouard  11605:  
1.180     brouard  11606: int hPijx(double *p, int bage, int fage){
                   11607:     /*------------- h Pij x at various ages ------------*/
                   11608: 
                   11609:   int stepsize;
                   11610:   int agelim;
                   11611:   int hstepm;
                   11612:   int nhstepm;
1.235     brouard  11613:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11614: 
                   11615:   double agedeb;
                   11616:   double ***p3mat;
                   11617: 
1.201     brouard  11618:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  11619:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11620:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11621:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11622:     }
                   11623:     printf("Computing pij: result on file '%s' \n", filerespij);
                   11624:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11625:   
                   11626:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11627:     /*if (stepm<=24) stepsize=2;*/
                   11628: 
                   11629:     agelim=AGESUP;
                   11630:     hstepm=stepsize*YEARM; /* Every year of age */
                   11631:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  11632:                
1.180     brouard  11633:     /* hstepm=1;   aff par mois*/
                   11634:     pstamp(ficrespij);
                   11635:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  11636:     i1= pow(2,cptcoveff);
1.218     brouard  11637:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11638:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11639:                /*      k=k+1;  */
1.235     brouard  11640:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11641:     for(k=1; k<=i1;k++){
1.253     brouard  11642:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11643:        continue;
1.183     brouard  11644:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  11645:       for(j=1;j<=cptcoveff;j++) 
1.332     brouard  11646:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  11647:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   11648:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11649:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   11650:       }
1.183     brouard  11651:       fprintf(ficrespij,"******\n");
                   11652:       
                   11653:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11654:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11655:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11656:        
                   11657:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  11658:        
1.183     brouard  11659:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11660:        oldm=oldms;savm=savms;
1.235     brouard  11661:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  11662:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11663:        for(i=1; i<=nlstate;i++)
                   11664:          for(j=1; j<=nlstate+ndeath;j++)
                   11665:            fprintf(ficrespij," %1d-%1d",i,j);
                   11666:        fprintf(ficrespij,"\n");
                   11667:        for (h=0; h<=nhstepm; h++){
                   11668:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11669:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  11670:          for(i=1; i<=nlstate;i++)
                   11671:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  11672:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  11673:          fprintf(ficrespij,"\n");
                   11674:        }
1.183     brouard  11675:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11676:        fprintf(ficrespij,"\n");
                   11677:       }
1.180     brouard  11678:       /*}*/
                   11679:     }
1.218     brouard  11680:     return 0;
1.180     brouard  11681: }
1.218     brouard  11682:  
                   11683:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11684:     /*------------- h Bij x at various ages ------------*/
                   11685: 
                   11686:   int stepsize;
1.218     brouard  11687:   /* int agelim; */
                   11688:        int ageminl;
1.217     brouard  11689:   int hstepm;
                   11690:   int nhstepm;
1.238     brouard  11691:   int h, i, i1, j, k, nres;
1.218     brouard  11692:        
1.217     brouard  11693:   double agedeb;
                   11694:   double ***p3mat;
1.218     brouard  11695:        
                   11696:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11697:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11698:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11699:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11700:   }
                   11701:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11702:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11703:   
                   11704:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11705:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11706:   
1.218     brouard  11707:   /* agelim=AGESUP; */
1.289     brouard  11708:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11709:   hstepm=stepsize*YEARM; /* Every year of age */
                   11710:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11711:   
                   11712:   /* hstepm=1;   aff par mois*/
                   11713:   pstamp(ficrespijb);
1.255     brouard  11714:   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  11715:   i1= pow(2,cptcoveff);
1.218     brouard  11716:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11717:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11718:   /*   k=k+1;  */
1.238     brouard  11719:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11720:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11721:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  11722:        continue;
                   11723:       fprintf(ficrespijb,"\n#****** ");
                   11724:       for(j=1;j<=cptcoveff;j++)
1.332     brouard  11725:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.238     brouard  11726:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  11727:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]);
1.238     brouard  11728:       }
                   11729:       fprintf(ficrespijb,"******\n");
1.264     brouard  11730:       if(invalidvarcomb[k]){  /* Is it necessary here? */
1.238     brouard  11731:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   11732:        continue;
                   11733:       }
                   11734:       
                   11735:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   11736:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   11737:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
1.297     brouard  11738:        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 */
                   11739:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
1.238     brouard  11740:        
                   11741:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   11742:        
1.266     brouard  11743:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   11744:        /* and memory limitations if stepm is small */
                   11745: 
1.238     brouard  11746:        /* oldm=oldms;savm=savms; */
                   11747:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.325     brouard  11748:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
1.238     brouard  11749:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  11750:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  11751:        for(i=1; i<=nlstate;i++)
                   11752:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  11753:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  11754:        fprintf(ficrespijb,"\n");
1.238     brouard  11755:        for (h=0; h<=nhstepm; h++){
                   11756:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11757:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   11758:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   11759:          for(i=1; i<=nlstate;i++)
                   11760:            for(j=1; j<=nlstate+ndeath;j++)
1.325     brouard  11761:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.238     brouard  11762:          fprintf(ficrespijb,"\n");
                   11763:        }
                   11764:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11765:        fprintf(ficrespijb,"\n");
                   11766:       } /* end age deb */
                   11767:     } /* end combination */
                   11768:   } /* end nres */
1.218     brouard  11769:   return 0;
                   11770:  } /*  hBijx */
1.217     brouard  11771: 
1.180     brouard  11772: 
1.136     brouard  11773: /***********************************************/
                   11774: /**************** Main Program *****************/
                   11775: /***********************************************/
                   11776: 
                   11777: int main(int argc, char *argv[])
                   11778: {
                   11779: #ifdef GSL
                   11780:   const gsl_multimin_fminimizer_type *T;
                   11781:   size_t iteri = 0, it;
                   11782:   int rval = GSL_CONTINUE;
                   11783:   int status = GSL_SUCCESS;
                   11784:   double ssval;
                   11785: #endif
                   11786:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  11787:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   11788:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  11789:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  11790:   int jj, ll, li, lj, lk;
1.136     brouard  11791:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  11792:   int num_filled;
1.136     brouard  11793:   int itimes;
                   11794:   int NDIM=2;
                   11795:   int vpopbased=0;
1.235     brouard  11796:   int nres=0;
1.258     brouard  11797:   int endishere=0;
1.277     brouard  11798:   int noffset=0;
1.274     brouard  11799:   int ncurrv=0; /* Temporary variable */
                   11800:   
1.164     brouard  11801:   char ca[32], cb[32];
1.136     brouard  11802:   /*  FILE *fichtm; *//* Html File */
                   11803:   /* FILE *ficgp;*/ /*Gnuplot File */
                   11804:   struct stat info;
1.191     brouard  11805:   double agedeb=0.;
1.194     brouard  11806: 
                   11807:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  11808:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  11809: 
1.165     brouard  11810:   double fret;
1.191     brouard  11811:   double dum=0.; /* Dummy variable */
1.136     brouard  11812:   double ***p3mat;
1.218     brouard  11813:   /* double ***mobaverage; */
1.319     brouard  11814:   double wald;
1.164     brouard  11815: 
                   11816:   char line[MAXLINE];
1.197     brouard  11817:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   11818: 
1.234     brouard  11819:   char  modeltemp[MAXLINE];
1.332     brouard  11820:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  11821:   
1.136     brouard  11822:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  11823:   char *tok, *val; /* pathtot */
1.334     brouard  11824:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  11825:   int c,  h , cpt, c2;
1.191     brouard  11826:   int jl=0;
                   11827:   int i1, j1, jk, stepsize=0;
1.194     brouard  11828:   int count=0;
                   11829: 
1.164     brouard  11830:   int *tab; 
1.136     brouard  11831:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  11832:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   11833:   /* double anprojf, mprojf, jprojf; */
                   11834:   /* double jintmean,mintmean,aintmean;   */
                   11835:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11836:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   11837:   double yrfproj= 10.0; /* Number of years of forward projections */
                   11838:   double yrbproj= 10.0; /* Number of years of backward projections */
                   11839:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  11840:   int mobilav=0,popforecast=0;
1.191     brouard  11841:   int hstepm=0, nhstepm=0;
1.136     brouard  11842:   int agemortsup;
                   11843:   float  sumlpop=0.;
                   11844:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   11845:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   11846: 
1.191     brouard  11847:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  11848:   double ftolpl=FTOL;
                   11849:   double **prlim;
1.217     brouard  11850:   double **bprlim;
1.317     brouard  11851:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   11852:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  11853:   double ***paramstart; /* Matrix of starting parameter values */
                   11854:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  11855:   double **matcov; /* Matrix of covariance */
1.203     brouard  11856:   double **hess; /* Hessian matrix */
1.136     brouard  11857:   double ***delti3; /* Scale */
                   11858:   double *delti; /* Scale */
                   11859:   double ***eij, ***vareij;
                   11860:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  11861: 
1.136     brouard  11862:   double *epj, vepp;
1.164     brouard  11863: 
1.273     brouard  11864:   double dateprev1, dateprev2;
1.296     brouard  11865:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   11866:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   11867: 
1.217     brouard  11868: 
1.136     brouard  11869:   double **ximort;
1.145     brouard  11870:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  11871:   int *dcwave;
                   11872: 
1.164     brouard  11873:   char z[1]="c";
1.136     brouard  11874: 
                   11875:   /*char  *strt;*/
                   11876:   char strtend[80];
1.126     brouard  11877: 
1.164     brouard  11878: 
1.126     brouard  11879: /*   setlocale (LC_ALL, ""); */
                   11880: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   11881: /*   textdomain (PACKAGE); */
                   11882: /*   setlocale (LC_CTYPE, ""); */
                   11883: /*   setlocale (LC_MESSAGES, ""); */
                   11884: 
                   11885:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  11886:   rstart_time = time(NULL);  
                   11887:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   11888:   start_time = *localtime(&rstart_time);
1.126     brouard  11889:   curr_time=start_time;
1.157     brouard  11890:   /*tml = *localtime(&start_time.tm_sec);*/
                   11891:   /* strcpy(strstart,asctime(&tml)); */
                   11892:   strcpy(strstart,asctime(&start_time));
1.126     brouard  11893: 
                   11894: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  11895: /*  tp.tm_sec = tp.tm_sec +86400; */
                   11896: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  11897: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   11898: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   11899: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  11900: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  11901: /*   strt=asctime(&tmg); */
                   11902: /*   printf("Time(after) =%s",strstart);  */
                   11903: /*  (void) time (&time_value);
                   11904: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   11905: *  tm = *localtime(&time_value);
                   11906: *  strstart=asctime(&tm);
                   11907: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   11908: */
                   11909: 
                   11910:   nberr=0; /* Number of errors and warnings */
                   11911:   nbwarn=0;
1.184     brouard  11912: #ifdef WIN32
                   11913:   _getcwd(pathcd, size);
                   11914: #else
1.126     brouard  11915:   getcwd(pathcd, size);
1.184     brouard  11916: #endif
1.191     brouard  11917:   syscompilerinfo(0);
1.196     brouard  11918:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  11919:   if(argc <=1){
                   11920:     printf("\nEnter the parameter file name: ");
1.205     brouard  11921:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   11922:       printf("ERROR Empty parameter file name\n");
                   11923:       goto end;
                   11924:     }
1.126     brouard  11925:     i=strlen(pathr);
                   11926:     if(pathr[i-1]=='\n')
                   11927:       pathr[i-1]='\0';
1.156     brouard  11928:     i=strlen(pathr);
1.205     brouard  11929:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  11930:       pathr[i-1]='\0';
1.205     brouard  11931:     }
                   11932:     i=strlen(pathr);
                   11933:     if( i==0 ){
                   11934:       printf("ERROR Empty parameter file name\n");
                   11935:       goto end;
                   11936:     }
                   11937:     for (tok = pathr; tok != NULL; ){
1.126     brouard  11938:       printf("Pathr |%s|\n",pathr);
                   11939:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   11940:       printf("val= |%s| pathr=%s\n",val,pathr);
                   11941:       strcpy (pathtot, val);
                   11942:       if(pathr[0] == '\0') break; /* Dirty */
                   11943:     }
                   11944:   }
1.281     brouard  11945:   else if (argc<=2){
                   11946:     strcpy(pathtot,argv[1]);
                   11947:   }
1.126     brouard  11948:   else{
                   11949:     strcpy(pathtot,argv[1]);
1.281     brouard  11950:     strcpy(z,argv[2]);
                   11951:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  11952:   }
                   11953:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   11954:   /*cygwin_split_path(pathtot,path,optionfile);
                   11955:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   11956:   /* cutv(path,optionfile,pathtot,'\\');*/
                   11957: 
                   11958:   /* Split argv[0], imach program to get pathimach */
                   11959:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   11960:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11961:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   11962:  /*   strcpy(pathimach,argv[0]); */
                   11963:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   11964:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   11965:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  11966: #ifdef WIN32
                   11967:   _chdir(path); /* Can be a relative path */
                   11968:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   11969: #else
1.126     brouard  11970:   chdir(path); /* Can be a relative path */
1.184     brouard  11971:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   11972: #endif
                   11973:   printf("Current directory %s!\n",pathcd);
1.126     brouard  11974:   strcpy(command,"mkdir ");
                   11975:   strcat(command,optionfilefiname);
                   11976:   if((outcmd=system(command)) != 0){
1.169     brouard  11977:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  11978:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   11979:     /* fclose(ficlog); */
                   11980: /*     exit(1); */
                   11981:   }
                   11982: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   11983: /*     perror("mkdir"); */
                   11984: /*   } */
                   11985: 
                   11986:   /*-------- arguments in the command line --------*/
                   11987: 
1.186     brouard  11988:   /* Main Log file */
1.126     brouard  11989:   strcat(filelog, optionfilefiname);
                   11990:   strcat(filelog,".log");    /* */
                   11991:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   11992:     printf("Problem with logfile %s\n",filelog);
                   11993:     goto end;
                   11994:   }
                   11995:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  11996:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  11997:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   11998:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   11999:  path=%s \n\
                   12000:  optionfile=%s\n\
                   12001:  optionfilext=%s\n\
1.156     brouard  12002:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12003: 
1.197     brouard  12004:   syscompilerinfo(1);
1.167     brouard  12005: 
1.126     brouard  12006:   printf("Local time (at start):%s",strstart);
                   12007:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12008:   fflush(ficlog);
                   12009: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12010: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12011: 
                   12012:   /* */
                   12013:   strcpy(fileres,"r");
                   12014:   strcat(fileres, optionfilefiname);
1.201     brouard  12015:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12016:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12017:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12018: 
1.186     brouard  12019:   /* Main ---------arguments file --------*/
1.126     brouard  12020: 
                   12021:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12022:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12023:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12024:     fflush(ficlog);
1.149     brouard  12025:     /* goto end; */
                   12026:     exit(70); 
1.126     brouard  12027:   }
                   12028: 
                   12029:   strcpy(filereso,"o");
1.201     brouard  12030:   strcat(filereso,fileresu);
1.126     brouard  12031:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12032:     printf("Problem with Output resultfile: %s\n", filereso);
                   12033:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12034:     fflush(ficlog);
                   12035:     goto end;
                   12036:   }
1.278     brouard  12037:       /*-------- Rewriting parameter file ----------*/
                   12038:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12039:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12040:   strcat(rfileres,".");    /* */
                   12041:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12042:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12043:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12044:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12045:     fflush(ficlog);
                   12046:     goto end;
                   12047:   }
                   12048:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12049: 
1.278     brouard  12050:                                      
1.126     brouard  12051:   /* Reads comments: lines beginning with '#' */
                   12052:   numlinepar=0;
1.277     brouard  12053:   /* Is it a BOM UTF-8 Windows file? */
                   12054:   /* First parameter line */
1.197     brouard  12055:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12056:     noffset=0;
                   12057:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12058:     {
                   12059:       noffset=noffset+3;
                   12060:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12061:     }
1.302     brouard  12062: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12063:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12064:     {
                   12065:       noffset=noffset+2;
                   12066:       printf("# File is an UTF16BE BOM file\n");
                   12067:     }
                   12068:     else if( line[0] == 0 && line[1] == 0)
                   12069:     {
                   12070:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12071:        noffset=noffset+4;
                   12072:        printf("# File is an UTF16BE BOM file\n");
                   12073:       }
                   12074:     } else{
                   12075:       ;/*printf(" Not a BOM file\n");*/
                   12076:     }
                   12077:   
1.197     brouard  12078:     /* If line starts with a # it is a comment */
1.277     brouard  12079:     if (line[noffset] == '#') {
1.197     brouard  12080:       numlinepar++;
                   12081:       fputs(line,stdout);
                   12082:       fputs(line,ficparo);
1.278     brouard  12083:       fputs(line,ficres);
1.197     brouard  12084:       fputs(line,ficlog);
                   12085:       continue;
                   12086:     }else
                   12087:       break;
                   12088:   }
                   12089:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12090:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12091:     if (num_filled != 5) {
                   12092:       printf("Should be 5 parameters\n");
1.283     brouard  12093:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12094:     }
1.126     brouard  12095:     numlinepar++;
1.197     brouard  12096:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12097:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12098:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12099:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12100:   }
                   12101:   /* Second parameter line */
                   12102:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12103:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12104:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12105:     if (line[0] == '#') {
                   12106:       numlinepar++;
1.283     brouard  12107:       printf("%s",line);
                   12108:       fprintf(ficres,"%s",line);
                   12109:       fprintf(ficparo,"%s",line);
                   12110:       fprintf(ficlog,"%s",line);
1.197     brouard  12111:       continue;
                   12112:     }else
                   12113:       break;
                   12114:   }
1.223     brouard  12115:   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", \
                   12116:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12117:     if (num_filled != 11) {
                   12118:       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  12119:       printf("but line=%s\n",line);
1.283     brouard  12120:       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");
                   12121:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12122:     }
1.286     brouard  12123:     if( lastpass > maxwav){
                   12124:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12125:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12126:       fflush(ficlog);
                   12127:       goto end;
                   12128:     }
                   12129:       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  12130:     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  12131:     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  12132:     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  12133:   }
1.203     brouard  12134:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12135:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12136:   /* Third parameter line */
                   12137:   while(fgets(line, MAXLINE, ficpar)) {
                   12138:     /* If line starts with a # it is a comment */
                   12139:     if (line[0] == '#') {
                   12140:       numlinepar++;
1.283     brouard  12141:       printf("%s",line);
                   12142:       fprintf(ficres,"%s",line);
                   12143:       fprintf(ficparo,"%s",line);
                   12144:       fprintf(ficlog,"%s",line);
1.197     brouard  12145:       continue;
                   12146:     }else
                   12147:       break;
                   12148:   }
1.201     brouard  12149:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12150:     if (num_filled != 1){
1.302     brouard  12151:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12152:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12153:       model[0]='\0';
                   12154:       goto end;
                   12155:     }
                   12156:     else{
                   12157:       if (model[0]=='+'){
                   12158:        for(i=1; i<=strlen(model);i++)
                   12159:          modeltemp[i-1]=model[i];
1.201     brouard  12160:        strcpy(model,modeltemp); 
1.197     brouard  12161:       }
                   12162:     }
1.199     brouard  12163:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12164:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12165:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12166:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12167:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12168:   }
                   12169:   /* 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); */
                   12170:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12171:   /* 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  12172:   /* 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); */
                   12173:   /* 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  12174:   fflush(ficlog);
1.190     brouard  12175:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12176:   if(model[0]=='#'){
1.279     brouard  12177:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12178:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12179:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12180:     if(mle != -1){
1.279     brouard  12181:       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  12182:       exit(1);
                   12183:     }
                   12184:   }
1.126     brouard  12185:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12186:     ungetc(c,ficpar);
                   12187:     fgets(line, MAXLINE, ficpar);
                   12188:     numlinepar++;
1.195     brouard  12189:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12190:       z[0]=line[1];
                   12191:     }
                   12192:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12193:     fputs(line, stdout);
                   12194:     //puts(line);
1.126     brouard  12195:     fputs(line,ficparo);
                   12196:     fputs(line,ficlog);
                   12197:   }
                   12198:   ungetc(c,ficpar);
                   12199: 
                   12200:    
1.290     brouard  12201:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12202:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12203:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12204:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12205:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12206:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12207:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12208:   */
                   12209:   if (strlen(model)>1) 
1.187     brouard  12210:     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  12211:   else
1.187     brouard  12212:     ncovmodel=2; /* Constant and age */
1.133     brouard  12213:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12214:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12215:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12216:     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);
                   12217:     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);
                   12218:     fflush(stdout);
                   12219:     fclose (ficlog);
                   12220:     goto end;
                   12221:   }
1.126     brouard  12222:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12223:   delti=delti3[1][1];
                   12224:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12225:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12226: /* We could also provide initial parameters values giving by simple logistic regression 
                   12227:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12228:       /* for(i=1;i<nlstate;i++){ */
                   12229:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12230:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12231:       /* } */
1.126     brouard  12232:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12233:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12234:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12235:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12236:     fclose (ficparo);
                   12237:     fclose (ficlog);
                   12238:     goto end;
                   12239:     exit(0);
1.220     brouard  12240:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12241:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12242:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12243:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12244:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12245:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12246:     hess=matrix(1,npar,1,npar);
1.220     brouard  12247:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12248:     /* Read guessed parameters */
1.126     brouard  12249:     /* Reads comments: lines beginning with '#' */
                   12250:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12251:       ungetc(c,ficpar);
                   12252:       fgets(line, MAXLINE, ficpar);
                   12253:       numlinepar++;
1.141     brouard  12254:       fputs(line,stdout);
1.126     brouard  12255:       fputs(line,ficparo);
                   12256:       fputs(line,ficlog);
                   12257:     }
                   12258:     ungetc(c,ficpar);
                   12259:     
                   12260:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12261:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12262:     for(i=1; i <=nlstate; i++){
1.234     brouard  12263:       j=0;
1.126     brouard  12264:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12265:        if(jj==i) continue;
                   12266:        j++;
1.292     brouard  12267:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12268:          ungetc(c,ficpar);
                   12269:          fgets(line, MAXLINE, ficpar);
                   12270:          numlinepar++;
                   12271:          fputs(line,stdout);
                   12272:          fputs(line,ficparo);
                   12273:          fputs(line,ficlog);
                   12274:        }
                   12275:        ungetc(c,ficpar);
1.234     brouard  12276:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12277:        if ((i1 != i) || (j1 != jj)){
                   12278:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12279: It might be a problem of design; if ncovcol and the model are correct\n \
                   12280: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12281:          exit(1);
                   12282:        }
                   12283:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12284:        if(mle==1)
                   12285:          printf("%1d%1d",i,jj);
                   12286:        fprintf(ficlog,"%1d%1d",i,jj);
                   12287:        for(k=1; k<=ncovmodel;k++){
                   12288:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12289:          if(mle==1){
                   12290:            printf(" %lf",param[i][j][k]);
                   12291:            fprintf(ficlog," %lf",param[i][j][k]);
                   12292:          }
                   12293:          else
                   12294:            fprintf(ficlog," %lf",param[i][j][k]);
                   12295:          fprintf(ficparo," %lf",param[i][j][k]);
                   12296:        }
                   12297:        fscanf(ficpar,"\n");
                   12298:        numlinepar++;
                   12299:        if(mle==1)
                   12300:          printf("\n");
                   12301:        fprintf(ficlog,"\n");
                   12302:        fprintf(ficparo,"\n");
1.126     brouard  12303:       }
                   12304:     }  
                   12305:     fflush(ficlog);
1.234     brouard  12306:     
1.251     brouard  12307:     /* Reads parameters values */
1.126     brouard  12308:     p=param[1][1];
1.251     brouard  12309:     pstart=paramstart[1][1];
1.126     brouard  12310:     
                   12311:     /* Reads comments: lines beginning with '#' */
                   12312:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12313:       ungetc(c,ficpar);
                   12314:       fgets(line, MAXLINE, ficpar);
                   12315:       numlinepar++;
1.141     brouard  12316:       fputs(line,stdout);
1.126     brouard  12317:       fputs(line,ficparo);
                   12318:       fputs(line,ficlog);
                   12319:     }
                   12320:     ungetc(c,ficpar);
                   12321: 
                   12322:     for(i=1; i <=nlstate; i++){
                   12323:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12324:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12325:        if ( (i1-i) * (j1-j) != 0){
                   12326:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12327:          exit(1);
                   12328:        }
                   12329:        printf("%1d%1d",i,j);
                   12330:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12331:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12332:        for(k=1; k<=ncovmodel;k++){
                   12333:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12334:          printf(" %le",delti3[i][j][k]);
                   12335:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12336:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12337:        }
                   12338:        fscanf(ficpar,"\n");
                   12339:        numlinepar++;
                   12340:        printf("\n");
                   12341:        fprintf(ficparo,"\n");
                   12342:        fprintf(ficlog,"\n");
1.126     brouard  12343:       }
                   12344:     }
                   12345:     fflush(ficlog);
1.234     brouard  12346:     
1.145     brouard  12347:     /* Reads covariance matrix */
1.126     brouard  12348:     delti=delti3[1][1];
1.220     brouard  12349:                
                   12350:                
1.126     brouard  12351:     /* 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  12352:                
1.126     brouard  12353:     /* Reads comments: lines beginning with '#' */
                   12354:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12355:       ungetc(c,ficpar);
                   12356:       fgets(line, MAXLINE, ficpar);
                   12357:       numlinepar++;
1.141     brouard  12358:       fputs(line,stdout);
1.126     brouard  12359:       fputs(line,ficparo);
                   12360:       fputs(line,ficlog);
                   12361:     }
                   12362:     ungetc(c,ficpar);
1.220     brouard  12363:                
1.126     brouard  12364:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12365:     hess=matrix(1,npar,1,npar);
1.131     brouard  12366:     for(i=1; i <=npar; i++)
                   12367:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12368:                
1.194     brouard  12369:     /* Scans npar lines */
1.126     brouard  12370:     for(i=1; i <=npar; i++){
1.226     brouard  12371:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12372:       if(count != 3){
1.226     brouard  12373:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12374: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12375: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12376:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12377: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12378: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12379:        exit(1);
1.220     brouard  12380:       }else{
1.226     brouard  12381:        if(mle==1)
                   12382:          printf("%1d%1d%d",i1,j1,jk);
                   12383:       }
                   12384:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12385:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12386:       for(j=1; j <=i; j++){
1.226     brouard  12387:        fscanf(ficpar," %le",&matcov[i][j]);
                   12388:        if(mle==1){
                   12389:          printf(" %.5le",matcov[i][j]);
                   12390:        }
                   12391:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12392:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12393:       }
                   12394:       fscanf(ficpar,"\n");
                   12395:       numlinepar++;
                   12396:       if(mle==1)
1.220     brouard  12397:                                printf("\n");
1.126     brouard  12398:       fprintf(ficlog,"\n");
                   12399:       fprintf(ficparo,"\n");
                   12400:     }
1.194     brouard  12401:     /* End of read covariance matrix npar lines */
1.126     brouard  12402:     for(i=1; i <=npar; i++)
                   12403:       for(j=i+1;j<=npar;j++)
1.226     brouard  12404:        matcov[i][j]=matcov[j][i];
1.126     brouard  12405:     
                   12406:     if(mle==1)
                   12407:       printf("\n");
                   12408:     fprintf(ficlog,"\n");
                   12409:     
                   12410:     fflush(ficlog);
                   12411:     
                   12412:   }    /* End of mle != -3 */
1.218     brouard  12413:   
1.186     brouard  12414:   /*  Main data
                   12415:    */
1.290     brouard  12416:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12417:   /* num=lvector(1,n); */
                   12418:   /* moisnais=vector(1,n); */
                   12419:   /* annais=vector(1,n); */
                   12420:   /* moisdc=vector(1,n); */
                   12421:   /* andc=vector(1,n); */
                   12422:   /* weight=vector(1,n); */
                   12423:   /* agedc=vector(1,n); */
                   12424:   /* cod=ivector(1,n); */
                   12425:   /* for(i=1;i<=n;i++){ */
                   12426:   num=lvector(firstobs,lastobs);
                   12427:   moisnais=vector(firstobs,lastobs);
                   12428:   annais=vector(firstobs,lastobs);
                   12429:   moisdc=vector(firstobs,lastobs);
                   12430:   andc=vector(firstobs,lastobs);
                   12431:   weight=vector(firstobs,lastobs);
                   12432:   agedc=vector(firstobs,lastobs);
                   12433:   cod=ivector(firstobs,lastobs);
                   12434:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12435:     num[i]=0;
                   12436:     moisnais[i]=0;
                   12437:     annais[i]=0;
                   12438:     moisdc[i]=0;
                   12439:     andc[i]=0;
                   12440:     agedc[i]=0;
                   12441:     cod[i]=0;
                   12442:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12443:   }
1.290     brouard  12444:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12445:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12446:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   12447:   printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel));
1.126     brouard  12448:   tab=ivector(1,NCOVMAX);
1.144     brouard  12449:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12450:   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  12451: 
1.136     brouard  12452:   /* Reads data from file datafile */
                   12453:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12454:     goto end;
                   12455: 
                   12456:   /* Calculation of the number of parameters from char model */
1.234     brouard  12457:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12458:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12459:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12460:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12461:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12462:   */
                   12463:   
                   12464:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12465:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12466:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335   ! brouard  12467:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12468:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12469:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12470:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12471:   TvarF=ivector(1,NCOVMAX); /*  */
                   12472:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12473:   TvarV=ivector(1,NCOVMAX); /*  */
                   12474:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12475:   TvarA=ivector(1,NCOVMAX); /*  */
                   12476:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12477:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12478:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12479:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12480:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12481:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12482:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12483:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12484:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   12485: 
1.230     brouard  12486:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12487:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12488:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12489:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12490:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12491:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12492:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12493:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12494:   */
                   12495:   /* For model-covariate k tells which data-covariate to use but
                   12496:     because this model-covariate is a construction we invent a new column
                   12497:     ncovcol + k1
                   12498:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12499:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12500:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12501:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12502:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12503:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12504:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12505:   */
1.145     brouard  12506:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12507:   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  12508:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12509:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12510:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12511:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12512:                         4 covariates (3 plus signs)
                   12513:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12514:                           */  
                   12515:   for(i=1;i<NCOVMAX;i++)
                   12516:     Tage[i]=0;
1.230     brouard  12517:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12518:                                * individual dummy, fixed or varying:
                   12519:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12520:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12521:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12522:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12523:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12524:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12525:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12526:                                * individual quantitative, fixed or varying:
                   12527:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12528:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12529:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12530: /* Main decodemodel */
                   12531: 
1.187     brouard  12532: 
1.223     brouard  12533:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12534:     goto end;
                   12535: 
1.137     brouard  12536:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12537:     nbwarn++;
                   12538:     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); 
                   12539:     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); 
                   12540:   }
1.136     brouard  12541:     /*  if(mle==1){*/
1.137     brouard  12542:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12543:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12544:   }
                   12545: 
                   12546:     /*-calculation of age at interview from date of interview and age at death -*/
                   12547:   agev=matrix(1,maxwav,1,imx);
                   12548: 
                   12549:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12550:     goto end;
                   12551: 
1.126     brouard  12552: 
1.136     brouard  12553:   agegomp=(int)agemin;
1.290     brouard  12554:   free_vector(moisnais,firstobs,lastobs);
                   12555:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12556:   /* free_matrix(mint,1,maxwav,1,n);
                   12557:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12558:   /* free_vector(moisdc,1,n); */
                   12559:   /* free_vector(andc,1,n); */
1.145     brouard  12560:   /* */
                   12561:   
1.126     brouard  12562:   wav=ivector(1,imx);
1.214     brouard  12563:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12564:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12565:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12566:   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.*/
                   12567:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12568:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12569:    
                   12570:   /* Concatenates waves */
1.214     brouard  12571:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12572:      Death is a valid wave (if date is known).
                   12573:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12574:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12575:      and mw[mi+1][i]. dh depends on stepm.
                   12576:   */
                   12577: 
1.126     brouard  12578:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12579:   /* Concatenates waves */
1.145     brouard  12580:  
1.290     brouard  12581:   free_vector(moisdc,firstobs,lastobs);
                   12582:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12583: 
1.126     brouard  12584:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12585:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12586:   ncodemax[1]=1;
1.145     brouard  12587:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12588:   cptcoveff=0;
1.220     brouard  12589:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335   ! brouard  12590:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
1.227     brouard  12591:   }
                   12592:   
                   12593:   ncovcombmax=pow(2,cptcoveff);
                   12594:   invalidvarcomb=ivector(1, ncovcombmax); 
                   12595:   for(i=1;i<ncovcombmax;i++)
                   12596:     invalidvarcomb[i]=0;
                   12597:   
1.211     brouard  12598:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12599:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12600:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12601:   
1.200     brouard  12602:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12603:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12604:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12605:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12606:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12607:    * (currently 0 or 1) in the data.
                   12608:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12609:    * corresponding modality (h,j).
                   12610:    */
                   12611: 
1.145     brouard  12612:   h=0;
                   12613:   /*if (cptcovn > 0) */
1.126     brouard  12614:   m=pow(2,cptcoveff);
                   12615:  
1.144     brouard  12616:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12617:           * For k=4 covariates, h goes from 1 to m=2**k
                   12618:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12619:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12620:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12621:           *______________________________   *______________________
                   12622:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12623:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12624:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12625:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12626:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12627:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12628:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12629:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12630:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12631:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12632:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12633:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12634:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12635:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12636:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12637:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12638:           */                                     
1.212     brouard  12639:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12640:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12641:      * and the value of each covariate?
                   12642:      * V1=1, V2=1, V3=2, V4=1 ?
                   12643:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12644:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12645:      * In order to get the real value in the data, we use nbcode
                   12646:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12647:      * We are keeping this crazy system in order to be able (in the future?) 
                   12648:      * to have more than 2 values (0 or 1) for a covariate.
                   12649:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12650:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12651:      *              bbbbbbbb
                   12652:      *              76543210     
                   12653:      *   h-1        00000101 (6-1=5)
1.219     brouard  12654:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12655:      *           &
                   12656:      *     1        00000001 (1)
1.219     brouard  12657:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12658:      *          +1= 00000001 =1 
1.211     brouard  12659:      *
                   12660:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12661:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12662:      *    >>k'            11
                   12663:      *          &   00000001
                   12664:      *            = 00000001
                   12665:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12666:      * Reverse h=6 and m=16?
                   12667:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12668:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12669:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12670:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12671:      * V3=decodtabm(14,3,2**4)=2
                   12672:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12673:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12674:      *          &1 000000001
                   12675:      *           = 000000001
                   12676:      *         +1= 000000010 =2
                   12677:      *                  2211
                   12678:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12679:      *                  V3=2
1.220     brouard  12680:                 * codtabm and decodtabm are identical
1.211     brouard  12681:      */
                   12682: 
1.145     brouard  12683: 
                   12684:  free_ivector(Ndum,-1,NCOVMAX);
                   12685: 
                   12686: 
1.126     brouard  12687:     
1.186     brouard  12688:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12689:   strcpy(optionfilegnuplot,optionfilefiname);
                   12690:   if(mle==-3)
1.201     brouard  12691:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12692:   strcat(optionfilegnuplot,".gp");
                   12693: 
                   12694:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12695:     printf("Problem with file %s",optionfilegnuplot);
                   12696:   }
                   12697:   else{
1.204     brouard  12698:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12699:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12700:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12701:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12702:   }
                   12703:   /*  fclose(ficgp);*/
1.186     brouard  12704: 
                   12705: 
                   12706:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12707: 
                   12708:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12709:   if(mle==-3)
1.201     brouard  12710:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12711:   strcat(optionfilehtm,".htm");
                   12712:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12713:     printf("Problem with %s \n",optionfilehtm);
                   12714:     exit(0);
1.126     brouard  12715:   }
                   12716: 
                   12717:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   12718:   strcat(optionfilehtmcov,"-cov.htm");
                   12719:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   12720:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   12721:   }
                   12722:   else{
                   12723:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   12724: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12725: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  12726:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   12727:   }
                   12728: 
1.335   ! brouard  12729:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
        !          12730: <title>IMaCh %s</title></head>\n\
        !          12731:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
        !          12732: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
        !          12733: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
        !          12734: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
        !          12735: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
        !          12736:   
        !          12737:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  12738: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  12739: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.335   ! brouard  12740: This file: <a href=\"%s\">%s</a>Title=%s <br>Datafile=<a href=\"%s\">%s</a> Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  12741: \n\
                   12742: <hr  size=\"2\" color=\"#EC5E5E\">\
                   12743:  <ul><li><h4>Parameter files</h4>\n\
                   12744:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   12745:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   12746:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   12747:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   12748:  - Date and time at start: %s</ul>\n",\
1.335   ! brouard  12749:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  12750:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   12751:          fileres,fileres,\
                   12752:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   12753:   fflush(fichtm);
                   12754: 
                   12755:   strcpy(pathr,path);
                   12756:   strcat(pathr,optionfilefiname);
1.184     brouard  12757: #ifdef WIN32
                   12758:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   12759: #else
1.126     brouard  12760:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  12761: #endif
                   12762:          
1.126     brouard  12763:   
1.220     brouard  12764:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   12765:                 and for any valid combination of covariates
1.126     brouard  12766:      and prints on file fileres'p'. */
1.251     brouard  12767:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  12768:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  12769: 
                   12770:   fprintf(fichtm,"\n");
1.286     brouard  12771:   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  12772:          ftol, stepm);
                   12773:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   12774:   ncurrv=1;
                   12775:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   12776:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   12777:   ncurrv=i;
                   12778:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12779:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  12780:   ncurrv=i;
                   12781:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  12782:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  12783:   ncurrv=i;
                   12784:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   12785:   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", \
                   12786:           nlstate, ndeath, maxwav, mle, weightopt);
                   12787: 
                   12788:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   12789: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   12790: 
                   12791:   
1.317     brouard  12792:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  12793: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   12794: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  12795:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  12796:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  12797:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12798:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12799:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   12800:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  12801: 
1.126     brouard  12802:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   12803:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   12804:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   12805: 
                   12806:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  12807:   /* For mortality only */
1.126     brouard  12808:   if (mle==-3){
1.136     brouard  12809:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  12810:     for(i=1;i<=NDIM;i++)
                   12811:       for(j=1;j<=NDIM;j++)
                   12812:        ximort[i][j]=0.;
1.186     brouard  12813:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  12814:     cens=ivector(firstobs,lastobs);
                   12815:     ageexmed=vector(firstobs,lastobs);
                   12816:     agecens=vector(firstobs,lastobs);
                   12817:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  12818:                
1.126     brouard  12819:     for (i=1; i<=imx; i++){
                   12820:       dcwave[i]=-1;
                   12821:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  12822:        if (s[m][i]>nlstate) {
                   12823:          dcwave[i]=m;
                   12824:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   12825:          break;
                   12826:        }
1.126     brouard  12827:     }
1.226     brouard  12828:     
1.126     brouard  12829:     for (i=1; i<=imx; i++) {
                   12830:       if (wav[i]>0){
1.226     brouard  12831:        ageexmed[i]=agev[mw[1][i]][i];
                   12832:        j=wav[i];
                   12833:        agecens[i]=1.; 
                   12834:        
                   12835:        if (ageexmed[i]> 1 && wav[i] > 0){
                   12836:          agecens[i]=agev[mw[j][i]][i];
                   12837:          cens[i]= 1;
                   12838:        }else if (ageexmed[i]< 1) 
                   12839:          cens[i]= -1;
                   12840:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   12841:          cens[i]=0 ;
1.126     brouard  12842:       }
                   12843:       else cens[i]=-1;
                   12844:     }
                   12845:     
                   12846:     for (i=1;i<=NDIM;i++) {
                   12847:       for (j=1;j<=NDIM;j++)
1.226     brouard  12848:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  12849:     }
                   12850:     
1.302     brouard  12851:     p[1]=0.0268; p[NDIM]=0.083;
                   12852:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  12853:     
                   12854:     
1.136     brouard  12855: #ifdef GSL
                   12856:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  12857: #else
1.126     brouard  12858:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  12859: #endif
1.201     brouard  12860:     strcpy(filerespow,"POW-MORT_"); 
                   12861:     strcat(filerespow,fileresu);
1.126     brouard  12862:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   12863:       printf("Problem with resultfile: %s\n", filerespow);
                   12864:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   12865:     }
1.136     brouard  12866: #ifdef GSL
                   12867:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  12868: #else
1.126     brouard  12869:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  12870: #endif
1.126     brouard  12871:     /*  for (i=1;i<=nlstate;i++)
                   12872:        for(j=1;j<=nlstate+ndeath;j++)
                   12873:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   12874:     */
                   12875:     fprintf(ficrespow,"\n");
1.136     brouard  12876: #ifdef GSL
                   12877:     /* gsl starts here */ 
                   12878:     T = gsl_multimin_fminimizer_nmsimplex;
                   12879:     gsl_multimin_fminimizer *sfm = NULL;
                   12880:     gsl_vector *ss, *x;
                   12881:     gsl_multimin_function minex_func;
                   12882: 
                   12883:     /* Initial vertex size vector */
                   12884:     ss = gsl_vector_alloc (NDIM);
                   12885:     
                   12886:     if (ss == NULL){
                   12887:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   12888:     }
                   12889:     /* Set all step sizes to 1 */
                   12890:     gsl_vector_set_all (ss, 0.001);
                   12891: 
                   12892:     /* Starting point */
1.126     brouard  12893:     
1.136     brouard  12894:     x = gsl_vector_alloc (NDIM);
                   12895:     
                   12896:     if (x == NULL){
                   12897:       gsl_vector_free(ss);
                   12898:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   12899:     }
                   12900:   
                   12901:     /* Initialize method and iterate */
                   12902:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  12903:     /*     gsl_vector_set(x, 0, 0.0268); */
                   12904:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  12905:     gsl_vector_set(x, 0, p[1]);
                   12906:     gsl_vector_set(x, 1, p[2]);
                   12907: 
                   12908:     minex_func.f = &gompertz_f;
                   12909:     minex_func.n = NDIM;
                   12910:     minex_func.params = (void *)&p; /* ??? */
                   12911:     
                   12912:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   12913:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   12914:     
                   12915:     printf("Iterations beginning .....\n\n");
                   12916:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   12917: 
                   12918:     iteri=0;
                   12919:     while (rval == GSL_CONTINUE){
                   12920:       iteri++;
                   12921:       status = gsl_multimin_fminimizer_iterate(sfm);
                   12922:       
                   12923:       if (status) printf("error: %s\n", gsl_strerror (status));
                   12924:       fflush(0);
                   12925:       
                   12926:       if (status) 
                   12927:         break;
                   12928:       
                   12929:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   12930:       ssval = gsl_multimin_fminimizer_size (sfm);
                   12931:       
                   12932:       if (rval == GSL_SUCCESS)
                   12933:         printf ("converged to a local maximum at\n");
                   12934:       
                   12935:       printf("%5d ", iteri);
                   12936:       for (it = 0; it < NDIM; it++){
                   12937:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   12938:       }
                   12939:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   12940:     }
                   12941:     
                   12942:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   12943:     
                   12944:     gsl_vector_free(x); /* initial values */
                   12945:     gsl_vector_free(ss); /* inital step size */
                   12946:     for (it=0; it<NDIM; it++){
                   12947:       p[it+1]=gsl_vector_get(sfm->x,it);
                   12948:       fprintf(ficrespow," %.12lf", p[it]);
                   12949:     }
                   12950:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   12951: #endif
                   12952: #ifdef POWELL
                   12953:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   12954: #endif  
1.126     brouard  12955:     fclose(ficrespow);
                   12956:     
1.203     brouard  12957:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  12958: 
                   12959:     for(i=1; i <=NDIM; i++)
                   12960:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  12961:                                matcov[i][j]=matcov[j][i];
1.126     brouard  12962:     
                   12963:     printf("\nCovariance matrix\n ");
1.203     brouard  12964:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  12965:     for(i=1; i <=NDIM; i++) {
                   12966:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  12967:                                printf("%f ",matcov[i][j]);
                   12968:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  12969:       }
1.203     brouard  12970:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  12971:     }
                   12972:     
                   12973:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  12974:     for (i=1;i<=NDIM;i++) {
1.126     brouard  12975:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  12976:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   12977:     }
1.302     brouard  12978:     lsurv=vector(agegomp,AGESUP);
                   12979:     lpop=vector(agegomp,AGESUP);
                   12980:     tpop=vector(agegomp,AGESUP);
1.126     brouard  12981:     lsurv[agegomp]=100000;
                   12982:     
                   12983:     for (k=agegomp;k<=AGESUP;k++) {
                   12984:       agemortsup=k;
                   12985:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   12986:     }
                   12987:     
                   12988:     for (k=agegomp;k<agemortsup;k++)
                   12989:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   12990:     
                   12991:     for (k=agegomp;k<agemortsup;k++){
                   12992:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   12993:       sumlpop=sumlpop+lpop[k];
                   12994:     }
                   12995:     
                   12996:     tpop[agegomp]=sumlpop;
                   12997:     for (k=agegomp;k<(agemortsup-3);k++){
                   12998:       /*  tpop[k+1]=2;*/
                   12999:       tpop[k+1]=tpop[k]-lpop[k];
                   13000:     }
                   13001:     
                   13002:     
                   13003:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13004:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13005:       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]);
                   13006:     
                   13007:     
                   13008:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13009:                ageminpar=50;
                   13010:                agemaxpar=100;
1.194     brouard  13011:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13012:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13013: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13014: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13015:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13016: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13017: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13018:     }else{
                   13019:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13020:                        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  13021:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13022:                }
1.201     brouard  13023:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13024:                     stepm, weightopt,\
                   13025:                     model,imx,p,matcov,agemortsup);
                   13026:     
1.302     brouard  13027:     free_vector(lsurv,agegomp,AGESUP);
                   13028:     free_vector(lpop,agegomp,AGESUP);
                   13029:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13030:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13031:     free_ivector(dcwave,firstobs,lastobs);
                   13032:     free_vector(agecens,firstobs,lastobs);
                   13033:     free_vector(ageexmed,firstobs,lastobs);
                   13034:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13035: #ifdef GSL
1.136     brouard  13036: #endif
1.186     brouard  13037:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13038:   /* Standard  */
                   13039:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13040:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13041:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13042:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13043:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13044:     for (k=1; k<=npar;k++)
                   13045:       printf(" %d %8.5f",k,p[k]);
                   13046:     printf("\n");
1.205     brouard  13047:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13048:       /* mlikeli uses func not funcone */
1.247     brouard  13049:       /* for(i=1;i<nlstate;i++){ */
                   13050:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13051:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13052:       /* } */
1.205     brouard  13053:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13054:     }
                   13055:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13056:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13057:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13058:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13059:     }
                   13060:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13061:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13062:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335   ! brouard  13063:           /* exit(0); */
1.126     brouard  13064:     for (k=1; k<=npar;k++)
                   13065:       printf(" %d %8.5f",k,p[k]);
                   13066:     printf("\n");
                   13067:     
                   13068:     /*--------- results files --------------*/
1.283     brouard  13069:     /* 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  13070:     
                   13071:     
                   13072:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13073:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13074:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13075: 
                   13076:     printf("#model=  1      +     age ");
                   13077:     fprintf(ficres,"#model=  1      +     age ");
                   13078:     fprintf(ficlog,"#model=  1      +     age ");
                   13079:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13080: </ul>", model);
                   13081: 
                   13082:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13083:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13084:     if(nagesqr==1){
                   13085:       printf("  + age*age  ");
                   13086:       fprintf(ficres,"  + age*age  ");
                   13087:       fprintf(ficlog,"  + age*age  ");
                   13088:       fprintf(fichtm, "<th>+ age*age</th>");
                   13089:     }
                   13090:     for(j=1;j <=ncovmodel-2;j++){
                   13091:       if(Typevar[j]==0) {
                   13092:        printf("  +      V%d  ",Tvar[j]);
                   13093:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13094:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13095:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13096:       }else if(Typevar[j]==1) {
                   13097:        printf("  +    V%d*age ",Tvar[j]);
                   13098:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13099:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13100:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13101:       }else if(Typevar[j]==2) {
                   13102:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13103:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13104:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13105:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13106:       }
                   13107:     }
                   13108:     printf("\n");
                   13109:     fprintf(ficres,"\n");
                   13110:     fprintf(ficlog,"\n");
                   13111:     fprintf(fichtm, "</tr>");
                   13112:     fprintf(fichtm, "\n");
                   13113:     
                   13114:     
1.126     brouard  13115:     for(i=1,jk=1; i <=nlstate; i++){
                   13116:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13117:        if (k != i) {
1.319     brouard  13118:          fprintf(fichtm, "<tr>");
1.225     brouard  13119:          printf("%d%d ",i,k);
                   13120:          fprintf(ficlog,"%d%d ",i,k);
                   13121:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13122:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13123:          for(j=1; j <=ncovmodel; j++){
                   13124:            printf("%12.7f ",p[jk]);
                   13125:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13126:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13127:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13128:            jk++; 
                   13129:          }
                   13130:          printf("\n");
                   13131:          fprintf(ficlog,"\n");
                   13132:          fprintf(ficres,"\n");
1.319     brouard  13133:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13134:        }
1.126     brouard  13135:       }
                   13136:     }
1.319     brouard  13137:     /* fprintf(fichtm,"</tr>\n"); */
                   13138:     fprintf(fichtm,"</table>\n");
                   13139:     fprintf(fichtm, "\n");
                   13140: 
1.203     brouard  13141:     if(mle != 0){
                   13142:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13143:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13144:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13145:       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");
                   13146:       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  13147:       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  13148:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13149:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13150:       if(nagesqr==1){
                   13151:        printf("  + age*age  ");
                   13152:        fprintf(ficres,"  + age*age  ");
                   13153:        fprintf(ficlog,"  + age*age  ");
                   13154:        fprintf(fichtm, "<th>+ age*age</th>");
                   13155:       }
                   13156:       for(j=1;j <=ncovmodel-2;j++){
                   13157:        if(Typevar[j]==0) {
                   13158:          printf("  +      V%d  ",Tvar[j]);
                   13159:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13160:        }else if(Typevar[j]==1) {
                   13161:          printf("  +    V%d*age ",Tvar[j]);
                   13162:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13163:        }else if(Typevar[j]==2) {
                   13164:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13165:        }
                   13166:       }
                   13167:       fprintf(fichtm, "</tr>\n");
                   13168:  
1.203     brouard  13169:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13170:        for(k=1; k <=(nlstate+ndeath); k++){
                   13171:          if (k != i) {
1.319     brouard  13172:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13173:            printf("%d%d ",i,k);
                   13174:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13175:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13176:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13177:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13178:              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]));
                   13179:              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  13180:              if(fabs(wald) > 1.96){
1.321     brouard  13181:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13182:              }else{
                   13183:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13184:              }
1.324     brouard  13185:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13186:              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  13187:              jk++; 
                   13188:            }
                   13189:            printf("\n");
                   13190:            fprintf(ficlog,"\n");
1.319     brouard  13191:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13192:          }
                   13193:        }
1.193     brouard  13194:       }
1.203     brouard  13195:     } /* end of hesscov and Wald tests */
1.319     brouard  13196:     fprintf(fichtm,"</table>\n");
1.225     brouard  13197:     
1.203     brouard  13198:     /*  */
1.126     brouard  13199:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13200:     printf("# Scales (for hessian or gradient estimation)\n");
                   13201:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13202:     for(i=1,jk=1; i <=nlstate; i++){
                   13203:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13204:        if (j!=i) {
                   13205:          fprintf(ficres,"%1d%1d",i,j);
                   13206:          printf("%1d%1d",i,j);
                   13207:          fprintf(ficlog,"%1d%1d",i,j);
                   13208:          for(k=1; k<=ncovmodel;k++){
                   13209:            printf(" %.5e",delti[jk]);
                   13210:            fprintf(ficlog," %.5e",delti[jk]);
                   13211:            fprintf(ficres," %.5e",delti[jk]);
                   13212:            jk++;
                   13213:          }
                   13214:          printf("\n");
                   13215:          fprintf(ficlog,"\n");
                   13216:          fprintf(ficres,"\n");
                   13217:        }
1.126     brouard  13218:       }
                   13219:     }
                   13220:     
                   13221:     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  13222:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13223:       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");
                   13224:     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");
                   13225:     /* # 121 Var(a12)\n\ */
                   13226:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13227:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13228:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13229:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13230:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13231:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13232:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13233:     
                   13234:     
                   13235:     /* Just to have a covariance matrix which will be more understandable
                   13236:        even is we still don't want to manage dictionary of variables
                   13237:     */
                   13238:     for(itimes=1;itimes<=2;itimes++){
                   13239:       jj=0;
                   13240:       for(i=1; i <=nlstate; i++){
1.225     brouard  13241:        for(j=1; j <=nlstate+ndeath; j++){
                   13242:          if(j==i) continue;
                   13243:          for(k=1; k<=ncovmodel;k++){
                   13244:            jj++;
                   13245:            ca[0]= k+'a'-1;ca[1]='\0';
                   13246:            if(itimes==1){
                   13247:              if(mle>=1)
                   13248:                printf("#%1d%1d%d",i,j,k);
                   13249:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13250:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13251:            }else{
                   13252:              if(mle>=1)
                   13253:                printf("%1d%1d%d",i,j,k);
                   13254:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13255:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13256:            }
                   13257:            ll=0;
                   13258:            for(li=1;li <=nlstate; li++){
                   13259:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13260:                if(lj==li) continue;
                   13261:                for(lk=1;lk<=ncovmodel;lk++){
                   13262:                  ll++;
                   13263:                  if(ll<=jj){
                   13264:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13265:                    if(ll<jj){
                   13266:                      if(itimes==1){
                   13267:                        if(mle>=1)
                   13268:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13269:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13270:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13271:                      }else{
                   13272:                        if(mle>=1)
                   13273:                          printf(" %.5e",matcov[jj][ll]); 
                   13274:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13275:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13276:                      }
                   13277:                    }else{
                   13278:                      if(itimes==1){
                   13279:                        if(mle>=1)
                   13280:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13281:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13282:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13283:                      }else{
                   13284:                        if(mle>=1)
                   13285:                          printf(" %.7e",matcov[jj][ll]); 
                   13286:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13287:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13288:                      }
                   13289:                    }
                   13290:                  }
                   13291:                } /* end lk */
                   13292:              } /* end lj */
                   13293:            } /* end li */
                   13294:            if(mle>=1)
                   13295:              printf("\n");
                   13296:            fprintf(ficlog,"\n");
                   13297:            fprintf(ficres,"\n");
                   13298:            numlinepar++;
                   13299:          } /* end k*/
                   13300:        } /*end j */
1.126     brouard  13301:       } /* end i */
                   13302:     } /* end itimes */
                   13303:     
                   13304:     fflush(ficlog);
                   13305:     fflush(ficres);
1.225     brouard  13306:     while(fgets(line, MAXLINE, ficpar)) {
                   13307:       /* If line starts with a # it is a comment */
                   13308:       if (line[0] == '#') {
                   13309:        numlinepar++;
                   13310:        fputs(line,stdout);
                   13311:        fputs(line,ficparo);
                   13312:        fputs(line,ficlog);
1.299     brouard  13313:        fputs(line,ficres);
1.225     brouard  13314:        continue;
                   13315:       }else
                   13316:        break;
                   13317:     }
                   13318:     
1.209     brouard  13319:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13320:     /*   ungetc(c,ficpar); */
                   13321:     /*   fgets(line, MAXLINE, ficpar); */
                   13322:     /*   fputs(line,stdout); */
                   13323:     /*   fputs(line,ficparo); */
                   13324:     /* } */
                   13325:     /* ungetc(c,ficpar); */
1.126     brouard  13326:     
                   13327:     estepm=0;
1.209     brouard  13328:     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  13329:       
                   13330:       if (num_filled != 6) {
                   13331:        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);
                   13332:        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);
                   13333:        goto end;
                   13334:       }
                   13335:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13336:     }
                   13337:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13338:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13339:     
1.209     brouard  13340:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13341:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13342:     if (fage <= 2) {
                   13343:       bage = ageminpar;
                   13344:       fage = agemaxpar;
                   13345:     }
                   13346:     
                   13347:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13348:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13349:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13350:                
1.186     brouard  13351:     /* Other stuffs, more or less useful */    
1.254     brouard  13352:     while(fgets(line, MAXLINE, ficpar)) {
                   13353:       /* If line starts with a # it is a comment */
                   13354:       if (line[0] == '#') {
                   13355:        numlinepar++;
                   13356:        fputs(line,stdout);
                   13357:        fputs(line,ficparo);
                   13358:        fputs(line,ficlog);
1.299     brouard  13359:        fputs(line,ficres);
1.254     brouard  13360:        continue;
                   13361:       }else
                   13362:        break;
                   13363:     }
                   13364: 
                   13365:     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){
                   13366:       
                   13367:       if (num_filled != 7) {
                   13368:        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);
                   13369:        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);
                   13370:        goto end;
                   13371:       }
                   13372:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13373:       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);
                   13374:       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);
                   13375:       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  13376:     }
1.254     brouard  13377: 
                   13378:     while(fgets(line, MAXLINE, ficpar)) {
                   13379:       /* If line starts with a # it is a comment */
                   13380:       if (line[0] == '#') {
                   13381:        numlinepar++;
                   13382:        fputs(line,stdout);
                   13383:        fputs(line,ficparo);
                   13384:        fputs(line,ficlog);
1.299     brouard  13385:        fputs(line,ficres);
1.254     brouard  13386:        continue;
                   13387:       }else
                   13388:        break;
1.126     brouard  13389:     }
                   13390:     
                   13391:     
                   13392:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13393:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13394:     
1.254     brouard  13395:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13396:       if (num_filled != 1) {
                   13397:        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);
                   13398:        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);
                   13399:        goto end;
                   13400:       }
                   13401:       printf("pop_based=%d\n",popbased);
                   13402:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13403:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13404:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13405:     }
                   13406:      
1.258     brouard  13407:     /* Results */
1.332     brouard  13408:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13409:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13410:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13411:     endishere=0;
1.258     brouard  13412:     nresult=0;
1.308     brouard  13413:     parameterline=0;
1.258     brouard  13414:     do{
                   13415:       if(!fgets(line, MAXLINE, ficpar)){
                   13416:        endishere=1;
1.308     brouard  13417:        parameterline=15;
1.258     brouard  13418:       }else if (line[0] == '#') {
                   13419:        /* If line starts with a # it is a comment */
1.254     brouard  13420:        numlinepar++;
                   13421:        fputs(line,stdout);
                   13422:        fputs(line,ficparo);
                   13423:        fputs(line,ficlog);
1.299     brouard  13424:        fputs(line,ficres);
1.254     brouard  13425:        continue;
1.258     brouard  13426:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13427:        parameterline=11;
1.296     brouard  13428:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13429:        parameterline=12;
1.307     brouard  13430:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13431:        parameterline=13;
1.307     brouard  13432:       }
1.258     brouard  13433:       else{
                   13434:        parameterline=14;
1.254     brouard  13435:       }
1.308     brouard  13436:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13437:       case 11:
1.296     brouard  13438:        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)){
                   13439:                  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  13440:          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);
                   13441:          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);
                   13442:          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);
                   13443:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13444:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13445:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13446:           prvforecast = 1;
                   13447:        } 
                   13448:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13449:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13450:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13451:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13452:           prvforecast = 2;
                   13453:        }
                   13454:        else {
                   13455:          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);
                   13456:          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);
                   13457:          goto end;
1.258     brouard  13458:        }
1.254     brouard  13459:        break;
1.258     brouard  13460:       case 12:
1.296     brouard  13461:        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)){
                   13462:           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);
                   13463:          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);
                   13464:          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);
                   13465:          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);
                   13466:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13467:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13468:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13469:           prvbackcast = 1;
                   13470:        } 
                   13471:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13472:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13473:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13474:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13475:           prvbackcast = 2;
                   13476:        }
                   13477:        else {
                   13478:          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);
                   13479:          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);
                   13480:          goto end;
1.258     brouard  13481:        }
1.230     brouard  13482:        break;
1.258     brouard  13483:       case 13:
1.332     brouard  13484:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13485:        nresult++; /* Sum of resultlines */
1.332     brouard  13486:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13487:        /* removefirstspace(&resultlineori); */
                   13488:        
                   13489:        if(strstr(resultlineori,"v") !=0){
                   13490:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13491:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13492:          return 1;
                   13493:        }
                   13494:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13495:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13496:        if(nresult > MAXRESULTLINESPONE-1){
                   13497:          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);
                   13498:          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  13499:          goto end;
                   13500:        }
1.332     brouard  13501:        
1.310     brouard  13502:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13503:          fprintf(ficparo,"result: %s\n",resultline);
                   13504:          fprintf(ficres,"result: %s\n",resultline);
                   13505:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13506:        } else
                   13507:          goto end;
1.307     brouard  13508:        break;
                   13509:       case 14:
                   13510:        printf("Error: Unknown command '%s'\n",line);
                   13511:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13512:        if(line[0] == ' ' || line[0] == '\n'){
                   13513:          printf("It should not be an empty line '%s'\n",line);
                   13514:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13515:        }         
1.307     brouard  13516:        if(ncovmodel >=2 && nresult==0 ){
                   13517:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13518:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13519:        }
1.307     brouard  13520:        /* goto end; */
                   13521:        break;
1.308     brouard  13522:       case 15:
                   13523:        printf("End of resultlines.\n");
                   13524:        fprintf(ficlog,"End of resultlines.\n");
                   13525:        break;
                   13526:       default: /* parameterline =0 */
1.307     brouard  13527:        nresult=1;
                   13528:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13529:       } /* End switch parameterline */
                   13530:     }while(endishere==0); /* End do */
1.126     brouard  13531:     
1.230     brouard  13532:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13533:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13534:     
                   13535:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13536:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13537:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13538: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13539: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13540:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13541: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13542: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13543:     }else{
1.270     brouard  13544:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13545:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13546:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13547:       if(prvforecast==1){
                   13548:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13549:         jprojd=jproj1;
                   13550:         mprojd=mproj1;
                   13551:         anprojd=anproj1;
                   13552:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13553:         jprojf=jproj2;
                   13554:         mprojf=mproj2;
                   13555:         anprojf=anproj2;
                   13556:       } else if(prvforecast == 2){
                   13557:         dateprojd=dateintmean;
                   13558:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13559:         dateprojf=dateintmean+yrfproj;
                   13560:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13561:       }
                   13562:       if(prvbackcast==1){
                   13563:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13564:         jbackd=jback1;
                   13565:         mbackd=mback1;
                   13566:         anbackd=anback1;
                   13567:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13568:         jbackf=jback2;
                   13569:         mbackf=mback2;
                   13570:         anbackf=anback2;
                   13571:       } else if(prvbackcast == 2){
                   13572:         datebackd=dateintmean;
                   13573:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13574:         datebackf=dateintmean-yrbproj;
                   13575:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13576:       }
                   13577:       
                   13578:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13579:     }
                   13580:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13581:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13582:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13583:                
1.225     brouard  13584:     /*------------ free_vector  -------------*/
                   13585:     /*  chdir(path); */
1.220     brouard  13586:                
1.215     brouard  13587:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13588:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13589:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13590:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13591:     free_lvector(num,firstobs,lastobs);
                   13592:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13593:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13594:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13595:     fclose(ficparo);
                   13596:     fclose(ficres);
1.220     brouard  13597:                
                   13598:                
1.186     brouard  13599:     /* Other results (useful)*/
1.220     brouard  13600:                
                   13601:                
1.126     brouard  13602:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13603:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13604:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13605:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13606:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13607:     fclose(ficrespl);
                   13608: 
                   13609:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13610:     /*#include "hpijx.h"*/
1.332     brouard  13611:     /** 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?*/
                   13612:     /* calls hpxij with combination k */
1.180     brouard  13613:     hPijx(p, bage, fage);
1.145     brouard  13614:     fclose(ficrespij);
1.227     brouard  13615:     
1.220     brouard  13616:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13617:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13618:     k=1;
1.126     brouard  13619:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13620:     
1.269     brouard  13621:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13622:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13623:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13624:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13625:        for(k=1;k<=ncovcombmax;k++)
                   13626:          probs[i][j][k]=0.;
1.269     brouard  13627:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13628:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13629:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13630:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13631:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13632:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13633:          for(k=1;k<=ncovcombmax;k++)
                   13634:            mobaverages[i][j][k]=0.;
1.219     brouard  13635:       mobaverage=mobaverages;
                   13636:       if (mobilav!=0) {
1.235     brouard  13637:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13638:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13639:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13640:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13641:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13642:        }
1.269     brouard  13643:       } else if (mobilavproj !=0) {
1.235     brouard  13644:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13645:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13646:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13647:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13648:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13649:        }
1.269     brouard  13650:       }else{
                   13651:        printf("Internal error moving average\n");
                   13652:        fflush(stdout);
                   13653:        exit(1);
1.219     brouard  13654:       }
                   13655:     }/* end if moving average */
1.227     brouard  13656:     
1.126     brouard  13657:     /*---------- Forecasting ------------------*/
1.296     brouard  13658:     if(prevfcast==1){ 
                   13659:       /*   /\*    if(stepm ==1){*\/ */
                   13660:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13661:       /*This done previously after freqsummary.*/
                   13662:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13663:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13664:       
                   13665:       /* } else if (prvforecast==2){ */
                   13666:       /*   /\*    if(stepm ==1){*\/ */
                   13667:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13668:       /* } */
                   13669:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13670:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13671:     }
1.269     brouard  13672: 
1.296     brouard  13673:     /* Prevbcasting */
                   13674:     if(prevbcast==1){
1.219     brouard  13675:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13676:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13677:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13678: 
                   13679:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13680: 
                   13681:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13682: 
1.219     brouard  13683:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13684:       fclose(ficresplb);
                   13685: 
1.222     brouard  13686:       hBijx(p, bage, fage, mobaverage);
                   13687:       fclose(ficrespijb);
1.219     brouard  13688: 
1.296     brouard  13689:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13690:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13691:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13692:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13693:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13694:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13695: 
                   13696:       
1.269     brouard  13697:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13698: 
                   13699:       
1.269     brouard  13700:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13701:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13702:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13703:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13704:     }    /* end  Prevbcasting */
1.268     brouard  13705:  
1.186     brouard  13706:  
                   13707:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13708: 
1.215     brouard  13709:     free_ivector(wav,1,imx);
                   13710:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13711:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13712:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13713:                
                   13714:                
1.127     brouard  13715:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  13716:                
1.201     brouard  13717:     strcpy(filerese,"E_");
                   13718:     strcat(filerese,fileresu);
1.126     brouard  13719:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   13720:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13721:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   13722:     }
1.208     brouard  13723:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   13724:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  13725: 
                   13726:     pstamp(ficreseij);
1.219     brouard  13727:                
1.235     brouard  13728:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13729:     if (cptcovn < 1){i1=1;}
                   13730:     
                   13731:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   13732:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  13733:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  13734:        continue;
1.219     brouard  13735:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  13736:       printf("\n#****** ");
1.225     brouard  13737:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  13738:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   13739:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  13740:       }
                   13741:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.334     brouard  13742:        printf(" V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   13743:        fprintf(ficreseij,"V%d=%f ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  13744:       }
                   13745:       fprintf(ficreseij,"******\n");
1.235     brouard  13746:       printf("******\n");
1.219     brouard  13747:       
                   13748:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13749:       oldm=oldms;savm=savms;
1.330     brouard  13750:       /* 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  13751:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  13752:       
1.219     brouard  13753:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  13754:     }
                   13755:     fclose(ficreseij);
1.208     brouard  13756:     printf("done evsij\n");fflush(stdout);
                   13757:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  13758: 
1.218     brouard  13759:                
1.227     brouard  13760:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  13761:                
1.201     brouard  13762:     strcpy(filerest,"T_");
                   13763:     strcat(filerest,fileresu);
1.127     brouard  13764:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   13765:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   13766:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   13767:     }
1.208     brouard  13768:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   13769:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  13770:     strcpy(fileresstde,"STDE_");
                   13771:     strcat(fileresstde,fileresu);
1.126     brouard  13772:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  13773:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   13774:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  13775:     }
1.227     brouard  13776:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   13777:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  13778: 
1.201     brouard  13779:     strcpy(filerescve,"CVE_");
                   13780:     strcat(filerescve,fileresu);
1.126     brouard  13781:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  13782:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   13783:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  13784:     }
1.227     brouard  13785:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   13786:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  13787: 
1.201     brouard  13788:     strcpy(fileresv,"V_");
                   13789:     strcat(fileresv,fileresu);
1.126     brouard  13790:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   13791:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13792:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   13793:     }
1.227     brouard  13794:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   13795:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  13796: 
1.235     brouard  13797:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13798:     if (cptcovn < 1){i1=1;}
                   13799:     
1.334     brouard  13800:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   13801:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   13802:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   13803:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   13804:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   13805:       /* */
                   13806:       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  13807:        continue;
1.321     brouard  13808:       printf("\n# model %s \n#****** Result for:", model);
                   13809:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   13810:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  13811:       /* It might not be a good idea to mix dummies and quantitative */
                   13812:       /* 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 *\/ */
                   13813:       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 */
                   13814:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   13815:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   13816:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   13817:         * (V5 is quanti) V4 and V3 are dummies
                   13818:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   13819:         *                                                              l=1 l=2
                   13820:         *                                                           k=1  1   1   0   0
                   13821:         *                                                           k=2  2   1   1   0
                   13822:         *                                                           k=3 [1] [2]  0   1
                   13823:         *                                                           k=4  2   2   1   1
                   13824:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   13825:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   13826:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   13827:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   13828:         */
                   13829:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   13830:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   13831: /* We give up with the combinations!! */
                   13832:        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 */
                   13833: 
                   13834:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
                   13835:          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  */
                   13836:          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  */
                   13837:          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  */
                   13838:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13839:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13840:          }else{
                   13841:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13842:          }
                   13843:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13844:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13845:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   13846:          /* For each selected (single) quantitative value */
                   13847:          printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   13848:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   13849:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   13850:          }else{
                   13851:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   13852:          }
                   13853:        }else{
                   13854:          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 */
                   13855:          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 */
                   13856:          exit(1);
                   13857:        }
1.335   ! brouard  13858:       } /* End loop for each variable in the resultline */
1.334     brouard  13859:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13860:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   13861:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13862:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13863:       /* }      */
1.208     brouard  13864:       fprintf(ficrest,"******\n");
1.227     brouard  13865:       fprintf(ficlog,"******\n");
                   13866:       printf("******\n");
1.208     brouard  13867:       
                   13868:       fprintf(ficresstdeij,"\n#****** ");
                   13869:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  13870:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  13871:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   13872:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13873:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13874:       }
                   13875:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
                   13876:        fprintf(ficresstdeij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   13877:        fprintf(ficrescveij," V%d=%f ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  13878:       }        
1.208     brouard  13879:       fprintf(ficresstdeij,"******\n");
                   13880:       fprintf(ficrescveij,"******\n");
                   13881:       
                   13882:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  13883:       /* pstamp(ficresvij); */
1.225     brouard  13884:       for(j=1;j<=cptcoveff;j++) 
1.335   ! brouard  13885:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
        !          13886:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  13887:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  13888:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   13889:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  13890:       }        
1.208     brouard  13891:       fprintf(ficresvij,"******\n");
                   13892:       
                   13893:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13894:       oldm=oldms;savm=savms;
1.235     brouard  13895:       printf(" cvevsij ");
                   13896:       fprintf(ficlog, " cvevsij ");
                   13897:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  13898:       printf(" end cvevsij \n ");
                   13899:       fprintf(ficlog, " end cvevsij \n ");
                   13900:       
                   13901:       /*
                   13902:        */
                   13903:       /* goto endfree; */
                   13904:       
                   13905:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   13906:       pstamp(ficrest);
                   13907:       
1.269     brouard  13908:       epj=vector(1,nlstate+1);
1.208     brouard  13909:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  13910:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   13911:        cptcod= 0; /* To be deleted */
                   13912:        printf("varevsij vpopbased=%d \n",vpopbased);
                   13913:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  13914:        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  13915:        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 ");
                   13916:        if(vpopbased==1)
                   13917:          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);
                   13918:        else
1.288     brouard  13919:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335   ! brouard  13920:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  13921:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   13922:        fprintf(ficrest,"\n");
                   13923:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  13924:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   13925:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  13926:        for(age=bage; age <=fage ;age++){
1.235     brouard  13927:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  13928:          if (vpopbased==1) {
                   13929:            if(mobilav ==0){
                   13930:              for(i=1; i<=nlstate;i++)
                   13931:                prlim[i][i]=probs[(int)age][i][k];
                   13932:            }else{ /* mobilav */ 
                   13933:              for(i=1; i<=nlstate;i++)
                   13934:                prlim[i][i]=mobaverage[(int)age][i][k];
                   13935:            }
                   13936:          }
1.219     brouard  13937:          
1.227     brouard  13938:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   13939:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   13940:          /* printf(" age %4.0f ",age); */
                   13941:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   13942:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   13943:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   13944:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   13945:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   13946:            }
                   13947:            epj[nlstate+1] +=epj[j];
                   13948:          }
                   13949:          /* printf(" age %4.0f \n",age); */
1.219     brouard  13950:          
1.227     brouard  13951:          for(i=1, vepp=0.;i <=nlstate;i++)
                   13952:            for(j=1;j <=nlstate;j++)
                   13953:              vepp += vareij[i][j][(int)age];
                   13954:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   13955:          for(j=1;j <=nlstate;j++){
                   13956:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   13957:          }
                   13958:          fprintf(ficrest,"\n");
                   13959:        }
1.208     brouard  13960:       } /* End vpopbased */
1.269     brouard  13961:       free_vector(epj,1,nlstate+1);
1.208     brouard  13962:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   13963:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  13964:       printf("done selection\n");fflush(stdout);
                   13965:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  13966:       
1.335   ! brouard  13967:     } /* End k selection or end covariate selection for nres */
1.227     brouard  13968: 
                   13969:     printf("done State-specific expectancies\n");fflush(stdout);
                   13970:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   13971: 
1.335   ! brouard  13972:     /* variance-covariance of forward period prevalence */
1.269     brouard  13973:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13974: 
1.227     brouard  13975:     
1.290     brouard  13976:     free_vector(weight,firstobs,lastobs);
1.330     brouard  13977:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  13978:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  13979:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   13980:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   13981:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   13982:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  13983:     free_ivector(tab,1,NCOVMAX);
                   13984:     fclose(ficresstdeij);
                   13985:     fclose(ficrescveij);
                   13986:     fclose(ficresvij);
                   13987:     fclose(ficrest);
                   13988:     fclose(ficpar);
                   13989:     
                   13990:     
1.126     brouard  13991:     /*---------- End : free ----------------*/
1.219     brouard  13992:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  13993:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   13994:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  13995:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   13996:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  13997:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  13998:   /* endfree:*/
                   13999:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14000:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14001:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  14002:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   14003:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14004:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14005:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14006:   free_matrix(matcov,1,npar,1,npar);
                   14007:   free_matrix(hess,1,npar,1,npar);
                   14008:   /*free_vector(delti,1,npar);*/
                   14009:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14010:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14011:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14012:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14013:   
                   14014:   free_ivector(ncodemax,1,NCOVMAX);
                   14015:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14016:   free_ivector(Dummy,-1,NCOVMAX);
                   14017:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14018:   free_ivector(DummyV,1,NCOVMAX);
                   14019:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14020:   free_ivector(Typevar,-1,NCOVMAX);
                   14021:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14022:   free_ivector(TvarsQ,1,NCOVMAX);
                   14023:   free_ivector(TvarsQind,1,NCOVMAX);
                   14024:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14025:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14026:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14027:   free_ivector(TvarFD,1,NCOVMAX);
                   14028:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14029:   free_ivector(TvarF,1,NCOVMAX);
                   14030:   free_ivector(TvarFind,1,NCOVMAX);
                   14031:   free_ivector(TvarV,1,NCOVMAX);
                   14032:   free_ivector(TvarVind,1,NCOVMAX);
                   14033:   free_ivector(TvarA,1,NCOVMAX);
                   14034:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14035:   free_ivector(TvarFQ,1,NCOVMAX);
                   14036:   free_ivector(TvarFQind,1,NCOVMAX);
                   14037:   free_ivector(TvarVD,1,NCOVMAX);
                   14038:   free_ivector(TvarVDind,1,NCOVMAX);
                   14039:   free_ivector(TvarVQ,1,NCOVMAX);
                   14040:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  14041:   free_ivector(Tvarsel,1,NCOVMAX);
                   14042:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14043:   free_ivector(Tposprod,1,NCOVMAX);
                   14044:   free_ivector(Tprod,1,NCOVMAX);
                   14045:   free_ivector(Tvaraff,1,NCOVMAX);
                   14046:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   14047:   free_ivector(Tage,1,NCOVMAX);
                   14048:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14049:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14050:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14051: 
                   14052:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14053: 
1.227     brouard  14054:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14055:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14056:   fflush(fichtm);
                   14057:   fflush(ficgp);
                   14058:   
1.227     brouard  14059:   
1.126     brouard  14060:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14061:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14062:     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  14063:   }else{
                   14064:     printf("End of Imach\n");
                   14065:     fprintf(ficlog,"End of Imach\n");
                   14066:   }
                   14067:   printf("See log file on %s\n",filelog);
                   14068:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14069:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14070:   rend_time = time(NULL);  
                   14071:   end_time = *localtime(&rend_time);
                   14072:   /* tml = *localtime(&end_time.tm_sec); */
                   14073:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14074:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14075:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14076:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14077:   
1.157     brouard  14078:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14079:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14080:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14081:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14082: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14083:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14084:   fclose(fichtm);
                   14085:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14086:   fclose(fichtmcov);
                   14087:   fclose(ficgp);
                   14088:   fclose(ficlog);
                   14089:   /*------ End -----------*/
1.227     brouard  14090:   
1.281     brouard  14091: 
                   14092: /* Executes gnuplot */
1.227     brouard  14093:   
                   14094:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14095: #ifdef WIN32
1.227     brouard  14096:   if (_chdir(pathcd) != 0)
                   14097:     printf("Can't move to directory %s!\n",path);
                   14098:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14099: #else
1.227     brouard  14100:     if(chdir(pathcd) != 0)
                   14101:       printf("Can't move to directory %s!\n", path);
                   14102:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14103: #endif 
1.126     brouard  14104:     printf("Current directory %s!\n",pathcd);
                   14105:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14106:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14107: #ifdef _WIN32
1.126     brouard  14108:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14109: #endif
                   14110:   if(!stat(plotcmd,&info)){
1.158     brouard  14111:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14112:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14113:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14114:     }else
                   14115:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14116: #ifdef __unix
1.126     brouard  14117:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14118:     if(!stat(plotcmd,&info)){
1.158     brouard  14119:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14120:     }else
                   14121:       strcpy(pplotcmd,plotcmd);
                   14122: #endif
                   14123:   }else
                   14124:     strcpy(pplotcmd,plotcmd);
                   14125:   
                   14126:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14127:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14128:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14129:   
1.126     brouard  14130:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14131:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14132:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14133:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14134:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14135:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14136:       strcpy(plotcmd,pplotcmd);
                   14137:     }
1.126     brouard  14138:   }
1.158     brouard  14139:   printf(" Successful, please wait...");
1.126     brouard  14140:   while (z[0] != 'q') {
                   14141:     /* chdir(path); */
1.154     brouard  14142:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14143:     scanf("%s",z);
                   14144: /*     if (z[0] == 'c') system("./imach"); */
                   14145:     if (z[0] == 'e') {
1.158     brouard  14146: #ifdef __APPLE__
1.152     brouard  14147:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14148: #elif __linux
                   14149:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14150: #else
1.152     brouard  14151:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14152: #endif
                   14153:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14154:       system(pplotcmd);
1.126     brouard  14155:     }
                   14156:     else if (z[0] == 'g') system(plotcmd);
                   14157:     else if (z[0] == 'q') exit(0);
                   14158:   }
1.227     brouard  14159: end:
1.126     brouard  14160:   while (z[0] != 'q') {
1.195     brouard  14161:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14162:     scanf("%s",z);
                   14163:   }
1.283     brouard  14164:   printf("End\n");
1.282     brouard  14165:   exit(0);
1.126     brouard  14166: }

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