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

1.348   ! brouard     1: /* $Id: imach.c,v 1.347 2022/09/18 14:36:44 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.348   ! brouard     4:   Revision 1.347  2022/09/18 14:36:44  brouard
        !             5:   Summary: version 0.99r42
        !             6: 
1.347     brouard     7:   Revision 1.346  2022/09/16 13:52:36  brouard
                      8:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                      9: 
1.346     brouard    10:   Revision 1.345  2022/09/16 13:40:11  brouard
                     11:   Summary: Version 0.99r41
                     12: 
                     13:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     14: 
1.345     brouard    15:   Revision 1.344  2022/09/14 19:33:30  brouard
                     16:   Summary: version 0.99r40
                     17: 
                     18:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     19: 
1.344     brouard    20:   Revision 1.343  2022/09/14 14:22:16  brouard
                     21:   Summary: version 0.99r39
                     22: 
                     23:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     24:   (fixed or time varying), using new last columns of
                     25:   ILK_parameter.txt file.
                     26: 
1.343     brouard    27:   Revision 1.342  2022/09/11 19:54:09  brouard
                     28:   Summary: 0.99r38
                     29: 
                     30:   * imach.c (Module): Adding timevarying products of any kinds,
                     31:   should work before shifting cotvar from ncovcol+nqv columns in
                     32:   order to have a correspondance between the column of cotvar and
                     33:   the id of column.
                     34:   (Module): Some cleaning and adding covariates in ILK.txt
                     35: 
1.342     brouard    36:   Revision 1.341  2022/09/11 07:58:42  brouard
                     37:   Summary: Version 0.99r38
                     38: 
                     39:   After adding change in cotvar.
                     40: 
1.341     brouard    41:   Revision 1.340  2022/09/11 07:53:11  brouard
                     42:   Summary: Version imach 0.99r37
                     43: 
                     44:   * imach.c (Module): Adding timevarying products of any kinds,
                     45:   should work before shifting cotvar from ncovcol+nqv columns in
                     46:   order to have a correspondance between the column of cotvar and
                     47:   the id of column.
                     48: 
1.340     brouard    49:   Revision 1.339  2022/09/09 17:55:22  brouard
                     50:   Summary: version 0.99r37
                     51: 
                     52:   * imach.c (Module): Many improvements for fixing products of fixed
                     53:   timevarying as well as fixed * fixed, and test with quantitative
                     54:   covariate.
                     55: 
1.339     brouard    56:   Revision 1.338  2022/09/04 17:40:33  brouard
                     57:   Summary: 0.99r36
                     58: 
                     59:   * imach.c (Module): Now the easy runs i.e. without result or
                     60:   model=1+age only did not work. The defautl combination should be 1
                     61:   and not 0 because everything hasn't been tranformed yet.
                     62: 
1.338     brouard    63:   Revision 1.337  2022/09/02 14:26:02  brouard
                     64:   Summary: version 0.99r35
                     65: 
                     66:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     67:   1+age+V1+V1*age for females and 1+age for females only
                     68:   (education=1 noweight)
                     69: 
1.337     brouard    70:   Revision 1.336  2022/08/31 09:52:36  brouard
                     71:   *** empty log message ***
                     72: 
1.336     brouard    73:   Revision 1.335  2022/08/31 08:23:16  brouard
                     74:   Summary: improvements...
                     75: 
1.335     brouard    76:   Revision 1.334  2022/08/25 09:08:41  brouard
                     77:   Summary: In progress for quantitative
                     78: 
1.334     brouard    79:   Revision 1.333  2022/08/21 09:10:30  brouard
                     80:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     81:   reassigning covariates: my first idea was that people will always
                     82:   use the first covariate V1 into the model but in fact they are
                     83:   producing data with many covariates and can use an equation model
                     84:   with some of the covariate; it means that in a model V2+V3 instead
                     85:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     86:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     87:   the equation model is restricted to two variables only (V2, V3)
                     88:   and the combination for V2 should be codtabm(k,1) instead of
                     89:   (codtabm(k,2), and the code should be
                     90:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     91:   made. All of these should be simplified once a day like we did in
                     92:   hpxij() for example by using precov[nres] which is computed in
                     93:   decoderesult for each nres of each resultline. Loop should be done
                     94:   on the equation model globally by distinguishing only product with
                     95:   age (which are changing with age) and no more on type of
                     96:   covariates, single dummies, single covariates.
                     97: 
1.333     brouard    98:   Revision 1.332  2022/08/21 09:06:25  brouard
                     99:   Summary: Version 0.99r33
                    100: 
                    101:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    102:   reassigning covariates: my first idea was that people will always
                    103:   use the first covariate V1 into the model but in fact they are
                    104:   producing data with many covariates and can use an equation model
                    105:   with some of the covariate; it means that in a model V2+V3 instead
                    106:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    107:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    108:   the equation model is restricted to two variables only (V2, V3)
                    109:   and the combination for V2 should be codtabm(k,1) instead of
                    110:   (codtabm(k,2), and the code should be
                    111:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    112:   made. All of these should be simplified once a day like we did in
                    113:   hpxij() for example by using precov[nres] which is computed in
                    114:   decoderesult for each nres of each resultline. Loop should be done
                    115:   on the equation model globally by distinguishing only product with
                    116:   age (which are changing with age) and no more on type of
                    117:   covariates, single dummies, single covariates.
                    118: 
1.332     brouard   119:   Revision 1.331  2022/08/07 05:40:09  brouard
                    120:   *** empty log message ***
                    121: 
1.331     brouard   122:   Revision 1.330  2022/08/06 07:18:25  brouard
                    123:   Summary: last 0.99r31
                    124: 
                    125:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    126: 
1.330     brouard   127:   Revision 1.329  2022/08/03 17:29:54  brouard
                    128:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    129: 
1.329     brouard   130:   Revision 1.328  2022/07/27 17:40:48  brouard
                    131:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    132: 
1.328     brouard   133:   Revision 1.327  2022/07/27 14:47:35  brouard
                    134:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    135: 
1.327     brouard   136:   Revision 1.326  2022/07/26 17:33:55  brouard
                    137:   Summary: some test with nres=1
                    138: 
1.326     brouard   139:   Revision 1.325  2022/07/25 14:27:23  brouard
                    140:   Summary: r30
                    141: 
                    142:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    143:   coredumped, revealed by Feiuno, thank you.
                    144: 
1.325     brouard   145:   Revision 1.324  2022/07/23 17:44:26  brouard
                    146:   *** empty log message ***
                    147: 
1.324     brouard   148:   Revision 1.323  2022/07/22 12:30:08  brouard
                    149:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    150: 
1.323     brouard   151:   Revision 1.322  2022/07/22 12:27:48  brouard
                    152:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    153: 
1.322     brouard   154:   Revision 1.321  2022/07/22 12:04:24  brouard
                    155:   Summary: r28
                    156: 
                    157:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    158: 
1.321     brouard   159:   Revision 1.320  2022/06/02 05:10:11  brouard
                    160:   *** empty log message ***
                    161: 
1.320     brouard   162:   Revision 1.319  2022/06/02 04:45:11  brouard
                    163:   * imach.c (Module): Adding the Wald tests from the log to the main
                    164:   htm for better display of the maximum likelihood estimators.
                    165: 
1.319     brouard   166:   Revision 1.318  2022/05/24 08:10:59  brouard
                    167:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    168:   of confidencce intervals with product in the equation modelC
                    169: 
1.318     brouard   170:   Revision 1.317  2022/05/15 15:06:23  brouard
                    171:   * imach.c (Module):  Some minor improvements
                    172: 
1.317     brouard   173:   Revision 1.316  2022/05/11 15:11:31  brouard
                    174:   Summary: r27
                    175: 
1.316     brouard   176:   Revision 1.315  2022/05/11 15:06:32  brouard
                    177:   *** empty log message ***
                    178: 
1.315     brouard   179:   Revision 1.314  2022/04/13 17:43:09  brouard
                    180:   * imach.c (Module): Adding link to text data files
                    181: 
1.314     brouard   182:   Revision 1.313  2022/04/11 15:57:42  brouard
                    183:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    184: 
1.313     brouard   185:   Revision 1.312  2022/04/05 21:24:39  brouard
                    186:   *** empty log message ***
                    187: 
1.312     brouard   188:   Revision 1.311  2022/04/05 21:03:51  brouard
                    189:   Summary: Fixed quantitative covariates
                    190: 
                    191:          Fixed covariates (dummy or quantitative)
                    192:        with missing values have never been allowed but are ERRORS and
                    193:        program quits. Standard deviations of fixed covariates were
                    194:        wrongly computed. Mean and standard deviations of time varying
                    195:        covariates are still not computed.
                    196: 
1.311     brouard   197:   Revision 1.310  2022/03/17 08:45:53  brouard
                    198:   Summary: 99r25
                    199: 
                    200:   Improving detection of errors: result lines should be compatible with
                    201:   the model.
                    202: 
1.310     brouard   203:   Revision 1.309  2021/05/20 12:39:14  brouard
                    204:   Summary: Version 0.99r24
                    205: 
1.309     brouard   206:   Revision 1.308  2021/03/31 13:11:57  brouard
                    207:   Summary: Version 0.99r23
                    208: 
                    209: 
                    210:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    211: 
1.308     brouard   212:   Revision 1.307  2021/03/08 18:11:32  brouard
                    213:   Summary: 0.99r22 fixed bug on result:
                    214: 
1.307     brouard   215:   Revision 1.306  2021/02/20 15:44:02  brouard
                    216:   Summary: Version 0.99r21
                    217: 
                    218:   * imach.c (Module): Fix bug on quitting after result lines!
                    219:   (Module): Version 0.99r21
                    220: 
1.306     brouard   221:   Revision 1.305  2021/02/20 15:28:30  brouard
                    222:   * imach.c (Module): Fix bug on quitting after result lines!
                    223: 
1.305     brouard   224:   Revision 1.304  2021/02/12 11:34:20  brouard
                    225:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    226: 
1.304     brouard   227:   Revision 1.303  2021/02/11 19:50:15  brouard
                    228:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    229: 
1.303     brouard   230:   Revision 1.302  2020/02/22 21:00:05  brouard
                    231:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    232:   and life table from the data without any state)
                    233: 
1.302     brouard   234:   Revision 1.301  2019/06/04 13:51:20  brouard
                    235:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    236: 
1.301     brouard   237:   Revision 1.300  2019/05/22 19:09:45  brouard
                    238:   Summary: version 0.99r19 of May 2019
                    239: 
1.300     brouard   240:   Revision 1.299  2019/05/22 18:37:08  brouard
                    241:   Summary: Cleaned 0.99r19
                    242: 
1.299     brouard   243:   Revision 1.298  2019/05/22 18:19:56  brouard
                    244:   *** empty log message ***
                    245: 
1.298     brouard   246:   Revision 1.297  2019/05/22 17:56:10  brouard
                    247:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    248: 
1.297     brouard   249:   Revision 1.296  2019/05/20 13:03:18  brouard
                    250:   Summary: Projection syntax simplified
                    251: 
                    252: 
                    253:   We can now start projections, forward or backward, from the mean date
                    254:   of inteviews up to or down to a number of years of projection:
                    255:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    256:   or
                    257:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    258:   or
                    259:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    260:   or
                    261:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    262: 
1.296     brouard   263:   Revision 1.295  2019/05/18 09:52:50  brouard
                    264:   Summary: doxygen tex bug
                    265: 
1.295     brouard   266:   Revision 1.294  2019/05/16 14:54:33  brouard
                    267:   Summary: There was some wrong lines added
                    268: 
1.294     brouard   269:   Revision 1.293  2019/05/09 15:17:34  brouard
                    270:   *** empty log message ***
                    271: 
1.293     brouard   272:   Revision 1.292  2019/05/09 14:17:20  brouard
                    273:   Summary: Some updates
                    274: 
1.292     brouard   275:   Revision 1.291  2019/05/09 13:44:18  brouard
                    276:   Summary: Before ncovmax
                    277: 
1.291     brouard   278:   Revision 1.290  2019/05/09 13:39:37  brouard
                    279:   Summary: 0.99r18 unlimited number of individuals
                    280: 
                    281:   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.
                    282: 
1.290     brouard   283:   Revision 1.289  2018/12/13 09:16:26  brouard
                    284:   Summary: Bug for young ages (<-30) will be in r17
                    285: 
1.289     brouard   286:   Revision 1.288  2018/05/02 20:58:27  brouard
                    287:   Summary: Some bugs fixed
                    288: 
1.288     brouard   289:   Revision 1.287  2018/05/01 17:57:25  brouard
                    290:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    291: 
1.287     brouard   292:   Revision 1.286  2018/04/27 14:27:04  brouard
                    293:   Summary: some minor bugs
                    294: 
1.286     brouard   295:   Revision 1.285  2018/04/21 21:02:16  brouard
                    296:   Summary: Some bugs fixed, valgrind tested
                    297: 
1.285     brouard   298:   Revision 1.284  2018/04/20 05:22:13  brouard
                    299:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    300: 
1.284     brouard   301:   Revision 1.283  2018/04/19 14:49:16  brouard
                    302:   Summary: Some minor bugs fixed
                    303: 
1.283     brouard   304:   Revision 1.282  2018/02/27 22:50:02  brouard
                    305:   *** empty log message ***
                    306: 
1.282     brouard   307:   Revision 1.281  2018/02/27 19:25:23  brouard
                    308:   Summary: Adding second argument for quitting
                    309: 
1.281     brouard   310:   Revision 1.280  2018/02/21 07:58:13  brouard
                    311:   Summary: 0.99r15
                    312: 
                    313:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    314: 
1.280     brouard   315:   Revision 1.279  2017/07/20 13:35:01  brouard
                    316:   Summary: temporary working
                    317: 
1.279     brouard   318:   Revision 1.278  2017/07/19 14:09:02  brouard
                    319:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    320: 
1.278     brouard   321:   Revision 1.277  2017/07/17 08:53:49  brouard
                    322:   Summary: BOM files can be read now
                    323: 
1.277     brouard   324:   Revision 1.276  2017/06/30 15:48:31  brouard
                    325:   Summary: Graphs improvements
                    326: 
1.276     brouard   327:   Revision 1.275  2017/06/30 13:39:33  brouard
                    328:   Summary: Saito's color
                    329: 
1.275     brouard   330:   Revision 1.274  2017/06/29 09:47:08  brouard
                    331:   Summary: Version 0.99r14
                    332: 
1.274     brouard   333:   Revision 1.273  2017/06/27 11:06:02  brouard
                    334:   Summary: More documentation on projections
                    335: 
1.273     brouard   336:   Revision 1.272  2017/06/27 10:22:40  brouard
                    337:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    338: 
1.272     brouard   339:   Revision 1.271  2017/06/27 10:17:50  brouard
                    340:   Summary: Some bug with rint
                    341: 
1.271     brouard   342:   Revision 1.270  2017/05/24 05:45:29  brouard
                    343:   *** empty log message ***
                    344: 
1.270     brouard   345:   Revision 1.269  2017/05/23 08:39:25  brouard
                    346:   Summary: Code into subroutine, cleanings
                    347: 
1.269     brouard   348:   Revision 1.268  2017/05/18 20:09:32  brouard
                    349:   Summary: backprojection and confidence intervals of backprevalence
                    350: 
1.268     brouard   351:   Revision 1.267  2017/05/13 10:25:05  brouard
                    352:   Summary: temporary save for backprojection
                    353: 
1.267     brouard   354:   Revision 1.266  2017/05/13 07:26:12  brouard
                    355:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    356: 
1.266     brouard   357:   Revision 1.265  2017/04/26 16:22:11  brouard
                    358:   Summary: imach 0.99r13 Some bugs fixed
                    359: 
1.265     brouard   360:   Revision 1.264  2017/04/26 06:01:29  brouard
                    361:   Summary: Labels in graphs
                    362: 
1.264     brouard   363:   Revision 1.263  2017/04/24 15:23:15  brouard
                    364:   Summary: to save
                    365: 
1.263     brouard   366:   Revision 1.262  2017/04/18 16:48:12  brouard
                    367:   *** empty log message ***
                    368: 
1.262     brouard   369:   Revision 1.261  2017/04/05 10:14:09  brouard
                    370:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    371: 
1.261     brouard   372:   Revision 1.260  2017/04/04 17:46:59  brouard
                    373:   Summary: Gnuplot indexations fixed (humm)
                    374: 
1.260     brouard   375:   Revision 1.259  2017/04/04 13:01:16  brouard
                    376:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    377: 
1.259     brouard   378:   Revision 1.258  2017/04/03 10:17:47  brouard
                    379:   Summary: Version 0.99r12
                    380: 
                    381:   Some cleanings, conformed with updated documentation.
                    382: 
1.258     brouard   383:   Revision 1.257  2017/03/29 16:53:30  brouard
                    384:   Summary: Temp
                    385: 
1.257     brouard   386:   Revision 1.256  2017/03/27 05:50:23  brouard
                    387:   Summary: Temporary
                    388: 
1.256     brouard   389:   Revision 1.255  2017/03/08 16:02:28  brouard
                    390:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    391: 
1.255     brouard   392:   Revision 1.254  2017/03/08 07:13:00  brouard
                    393:   Summary: Fixing data parameter line
                    394: 
1.254     brouard   395:   Revision 1.253  2016/12/15 11:59:41  brouard
                    396:   Summary: 0.99 in progress
                    397: 
1.253     brouard   398:   Revision 1.252  2016/09/15 21:15:37  brouard
                    399:   *** empty log message ***
                    400: 
1.252     brouard   401:   Revision 1.251  2016/09/15 15:01:13  brouard
                    402:   Summary: not working
                    403: 
1.251     brouard   404:   Revision 1.250  2016/09/08 16:07:27  brouard
                    405:   Summary: continue
                    406: 
1.250     brouard   407:   Revision 1.249  2016/09/07 17:14:18  brouard
                    408:   Summary: Starting values from frequencies
                    409: 
1.249     brouard   410:   Revision 1.248  2016/09/07 14:10:18  brouard
                    411:   *** empty log message ***
                    412: 
1.248     brouard   413:   Revision 1.247  2016/09/02 11:11:21  brouard
                    414:   *** empty log message ***
                    415: 
1.247     brouard   416:   Revision 1.246  2016/09/02 08:49:22  brouard
                    417:   *** empty log message ***
                    418: 
1.246     brouard   419:   Revision 1.245  2016/09/02 07:25:01  brouard
                    420:   *** empty log message ***
                    421: 
1.245     brouard   422:   Revision 1.244  2016/09/02 07:17:34  brouard
                    423:   *** empty log message ***
                    424: 
1.244     brouard   425:   Revision 1.243  2016/09/02 06:45:35  brouard
                    426:   *** empty log message ***
                    427: 
1.243     brouard   428:   Revision 1.242  2016/08/30 15:01:20  brouard
                    429:   Summary: Fixing a lots
                    430: 
1.242     brouard   431:   Revision 1.241  2016/08/29 17:17:25  brouard
                    432:   Summary: gnuplot problem in Back projection to fix
                    433: 
1.241     brouard   434:   Revision 1.240  2016/08/29 07:53:18  brouard
                    435:   Summary: Better
                    436: 
1.240     brouard   437:   Revision 1.239  2016/08/26 15:51:03  brouard
                    438:   Summary: Improvement in Powell output in order to copy and paste
                    439: 
                    440:   Author:
                    441: 
1.239     brouard   442:   Revision 1.238  2016/08/26 14:23:35  brouard
                    443:   Summary: Starting tests of 0.99
                    444: 
1.238     brouard   445:   Revision 1.237  2016/08/26 09:20:19  brouard
                    446:   Summary: to valgrind
                    447: 
1.237     brouard   448:   Revision 1.236  2016/08/25 10:50:18  brouard
                    449:   *** empty log message ***
                    450: 
1.236     brouard   451:   Revision 1.235  2016/08/25 06:59:23  brouard
                    452:   *** empty log message ***
                    453: 
1.235     brouard   454:   Revision 1.234  2016/08/23 16:51:20  brouard
                    455:   *** empty log message ***
                    456: 
1.234     brouard   457:   Revision 1.233  2016/08/23 07:40:50  brouard
                    458:   Summary: not working
                    459: 
1.233     brouard   460:   Revision 1.232  2016/08/22 14:20:21  brouard
                    461:   Summary: not working
                    462: 
1.232     brouard   463:   Revision 1.231  2016/08/22 07:17:15  brouard
                    464:   Summary: not working
                    465: 
1.231     brouard   466:   Revision 1.230  2016/08/22 06:55:53  brouard
                    467:   Summary: Not working
                    468: 
1.230     brouard   469:   Revision 1.229  2016/07/23 09:45:53  brouard
                    470:   Summary: Completing for func too
                    471: 
1.229     brouard   472:   Revision 1.228  2016/07/22 17:45:30  brouard
                    473:   Summary: Fixing some arrays, still debugging
                    474: 
1.227     brouard   475:   Revision 1.226  2016/07/12 18:42:34  brouard
                    476:   Summary: temp
                    477: 
1.226     brouard   478:   Revision 1.225  2016/07/12 08:40:03  brouard
                    479:   Summary: saving but not running
                    480: 
1.225     brouard   481:   Revision 1.224  2016/07/01 13:16:01  brouard
                    482:   Summary: Fixes
                    483: 
1.224     brouard   484:   Revision 1.223  2016/02/19 09:23:35  brouard
                    485:   Summary: temporary
                    486: 
1.223     brouard   487:   Revision 1.222  2016/02/17 08:14:50  brouard
                    488:   Summary: Probably last 0.98 stable version 0.98r6
                    489: 
1.222     brouard   490:   Revision 1.221  2016/02/15 23:35:36  brouard
                    491:   Summary: minor bug
                    492: 
1.220     brouard   493:   Revision 1.219  2016/02/15 00:48:12  brouard
                    494:   *** empty log message ***
                    495: 
1.219     brouard   496:   Revision 1.218  2016/02/12 11:29:23  brouard
                    497:   Summary: 0.99 Back projections
                    498: 
1.218     brouard   499:   Revision 1.217  2015/12/23 17:18:31  brouard
                    500:   Summary: Experimental backcast
                    501: 
1.217     brouard   502:   Revision 1.216  2015/12/18 17:32:11  brouard
                    503:   Summary: 0.98r4 Warning and status=-2
                    504: 
                    505:   Version 0.98r4 is now:
                    506:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    507:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    508:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    509: 
1.216     brouard   510:   Revision 1.215  2015/12/16 08:52:24  brouard
                    511:   Summary: 0.98r4 working
                    512: 
1.215     brouard   513:   Revision 1.214  2015/12/16 06:57:54  brouard
                    514:   Summary: temporary not working
                    515: 
1.214     brouard   516:   Revision 1.213  2015/12/11 18:22:17  brouard
                    517:   Summary: 0.98r4
                    518: 
1.213     brouard   519:   Revision 1.212  2015/11/21 12:47:24  brouard
                    520:   Summary: minor typo
                    521: 
1.212     brouard   522:   Revision 1.211  2015/11/21 12:41:11  brouard
                    523:   Summary: 0.98r3 with some graph of projected cross-sectional
                    524: 
                    525:   Author: Nicolas Brouard
                    526: 
1.211     brouard   527:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   528:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   529:   Summary: Adding ftolpl parameter
                    530:   Author: N Brouard
                    531: 
                    532:   We had difficulties to get smoothed confidence intervals. It was due
                    533:   to the period prevalence which wasn't computed accurately. The inner
                    534:   parameter ftolpl is now an outer parameter of the .imach parameter
                    535:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    536:   computation are long.
                    537: 
1.209     brouard   538:   Revision 1.208  2015/11/17 14:31:57  brouard
                    539:   Summary: temporary
                    540: 
1.208     brouard   541:   Revision 1.207  2015/10/27 17:36:57  brouard
                    542:   *** empty log message ***
                    543: 
1.207     brouard   544:   Revision 1.206  2015/10/24 07:14:11  brouard
                    545:   *** empty log message ***
                    546: 
1.206     brouard   547:   Revision 1.205  2015/10/23 15:50:53  brouard
                    548:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    549: 
1.205     brouard   550:   Revision 1.204  2015/10/01 16:20:26  brouard
                    551:   Summary: Some new graphs of contribution to likelihood
                    552: 
1.204     brouard   553:   Revision 1.203  2015/09/30 17:45:14  brouard
                    554:   Summary: looking at better estimation of the hessian
                    555: 
                    556:   Also a better criteria for convergence to the period prevalence And
                    557:   therefore adding the number of years needed to converge. (The
                    558:   prevalence in any alive state shold sum to one
                    559: 
1.203     brouard   560:   Revision 1.202  2015/09/22 19:45:16  brouard
                    561:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    562: 
1.202     brouard   563:   Revision 1.201  2015/09/15 17:34:58  brouard
                    564:   Summary: 0.98r0
                    565: 
                    566:   - Some new graphs like suvival functions
                    567:   - Some bugs fixed like model=1+age+V2.
                    568: 
1.201     brouard   569:   Revision 1.200  2015/09/09 16:53:55  brouard
                    570:   Summary: Big bug thanks to Flavia
                    571: 
                    572:   Even model=1+age+V2. did not work anymore
                    573: 
1.200     brouard   574:   Revision 1.199  2015/09/07 14:09:23  brouard
                    575:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    576: 
1.199     brouard   577:   Revision 1.198  2015/09/03 07:14:39  brouard
                    578:   Summary: 0.98q5 Flavia
                    579: 
1.198     brouard   580:   Revision 1.197  2015/09/01 18:24:39  brouard
                    581:   *** empty log message ***
                    582: 
1.197     brouard   583:   Revision 1.196  2015/08/18 23:17:52  brouard
                    584:   Summary: 0.98q5
                    585: 
1.196     brouard   586:   Revision 1.195  2015/08/18 16:28:39  brouard
                    587:   Summary: Adding a hack for testing purpose
                    588: 
                    589:   After reading the title, ftol and model lines, if the comment line has
                    590:   a q, starting with #q, the answer at the end of the run is quit. It
                    591:   permits to run test files in batch with ctest. The former workaround was
                    592:   $ echo q | imach foo.imach
                    593: 
1.195     brouard   594:   Revision 1.194  2015/08/18 13:32:00  brouard
                    595:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    596: 
1.194     brouard   597:   Revision 1.193  2015/08/04 07:17:42  brouard
                    598:   Summary: 0.98q4
                    599: 
1.193     brouard   600:   Revision 1.192  2015/07/16 16:49:02  brouard
                    601:   Summary: Fixing some outputs
                    602: 
1.192     brouard   603:   Revision 1.191  2015/07/14 10:00:33  brouard
                    604:   Summary: Some fixes
                    605: 
1.191     brouard   606:   Revision 1.190  2015/05/05 08:51:13  brouard
                    607:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    608: 
                    609:   Fix 1+age+.
                    610: 
1.190     brouard   611:   Revision 1.189  2015/04/30 14:45:16  brouard
                    612:   Summary: 0.98q2
                    613: 
1.189     brouard   614:   Revision 1.188  2015/04/30 08:27:53  brouard
                    615:   *** empty log message ***
                    616: 
1.188     brouard   617:   Revision 1.187  2015/04/29 09:11:15  brouard
                    618:   *** empty log message ***
                    619: 
1.187     brouard   620:   Revision 1.186  2015/04/23 12:01:52  brouard
                    621:   Summary: V1*age is working now, version 0.98q1
                    622: 
                    623:   Some codes had been disabled in order to simplify and Vn*age was
                    624:   working in the optimization phase, ie, giving correct MLE parameters,
                    625:   but, as usual, outputs were not correct and program core dumped.
                    626: 
1.186     brouard   627:   Revision 1.185  2015/03/11 13:26:42  brouard
                    628:   Summary: Inclusion of compile and links command line for Intel Compiler
                    629: 
1.185     brouard   630:   Revision 1.184  2015/03/11 11:52:39  brouard
                    631:   Summary: Back from Windows 8. Intel Compiler
                    632: 
1.184     brouard   633:   Revision 1.183  2015/03/10 20:34:32  brouard
                    634:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    635: 
                    636:   We use directest instead of original Powell test; probably no
                    637:   incidence on the results, but better justifications;
                    638:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    639:   wrong results.
                    640: 
1.183     brouard   641:   Revision 1.182  2015/02/12 08:19:57  brouard
                    642:   Summary: Trying to keep directest which seems simpler and more general
                    643:   Author: Nicolas Brouard
                    644: 
1.182     brouard   645:   Revision 1.181  2015/02/11 23:22:24  brouard
                    646:   Summary: Comments on Powell added
                    647: 
                    648:   Author:
                    649: 
1.181     brouard   650:   Revision 1.180  2015/02/11 17:33:45  brouard
                    651:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    652: 
1.180     brouard   653:   Revision 1.179  2015/01/04 09:57:06  brouard
                    654:   Summary: back to OS/X
                    655: 
1.179     brouard   656:   Revision 1.178  2015/01/04 09:35:48  brouard
                    657:   *** empty log message ***
                    658: 
1.178     brouard   659:   Revision 1.177  2015/01/03 18:40:56  brouard
                    660:   Summary: Still testing ilc32 on OSX
                    661: 
1.177     brouard   662:   Revision 1.176  2015/01/03 16:45:04  brouard
                    663:   *** empty log message ***
                    664: 
1.176     brouard   665:   Revision 1.175  2015/01/03 16:33:42  brouard
                    666:   *** empty log message ***
                    667: 
1.175     brouard   668:   Revision 1.174  2015/01/03 16:15:49  brouard
                    669:   Summary: Still in cross-compilation
                    670: 
1.174     brouard   671:   Revision 1.173  2015/01/03 12:06:26  brouard
                    672:   Summary: trying to detect cross-compilation
                    673: 
1.173     brouard   674:   Revision 1.172  2014/12/27 12:07:47  brouard
                    675:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    676: 
1.172     brouard   677:   Revision 1.171  2014/12/23 13:26:59  brouard
                    678:   Summary: Back from Visual C
                    679: 
                    680:   Still problem with utsname.h on Windows
                    681: 
1.171     brouard   682:   Revision 1.170  2014/12/23 11:17:12  brouard
                    683:   Summary: Cleaning some \%% back to %%
                    684: 
                    685:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    686: 
1.170     brouard   687:   Revision 1.169  2014/12/22 23:08:31  brouard
                    688:   Summary: 0.98p
                    689: 
                    690:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    691: 
1.169     brouard   692:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   693:   Summary: update
1.169     brouard   694: 
1.168     brouard   695:   Revision 1.167  2014/12/22 13:50:56  brouard
                    696:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    697: 
                    698:   Testing on Linux 64
                    699: 
1.167     brouard   700:   Revision 1.166  2014/12/22 11:40:47  brouard
                    701:   *** empty log message ***
                    702: 
1.166     brouard   703:   Revision 1.165  2014/12/16 11:20:36  brouard
                    704:   Summary: After compiling on Visual C
                    705: 
                    706:   * imach.c (Module): Merging 1.61 to 1.162
                    707: 
1.165     brouard   708:   Revision 1.164  2014/12/16 10:52:11  brouard
                    709:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    710: 
                    711:   * imach.c (Module): Merging 1.61 to 1.162
                    712: 
1.164     brouard   713:   Revision 1.163  2014/12/16 10:30:11  brouard
                    714:   * imach.c (Module): Merging 1.61 to 1.162
                    715: 
1.163     brouard   716:   Revision 1.162  2014/09/25 11:43:39  brouard
                    717:   Summary: temporary backup 0.99!
                    718: 
1.162     brouard   719:   Revision 1.1  2014/09/16 11:06:58  brouard
                    720:   Summary: With some code (wrong) for nlopt
                    721: 
                    722:   Author:
                    723: 
                    724:   Revision 1.161  2014/09/15 20:41:41  brouard
                    725:   Summary: Problem with macro SQR on Intel compiler
                    726: 
1.161     brouard   727:   Revision 1.160  2014/09/02 09:24:05  brouard
                    728:   *** empty log message ***
                    729: 
1.160     brouard   730:   Revision 1.159  2014/09/01 10:34:10  brouard
                    731:   Summary: WIN32
                    732:   Author: Brouard
                    733: 
1.159     brouard   734:   Revision 1.158  2014/08/27 17:11:51  brouard
                    735:   *** empty log message ***
                    736: 
1.158     brouard   737:   Revision 1.157  2014/08/27 16:26:55  brouard
                    738:   Summary: Preparing windows Visual studio version
                    739:   Author: Brouard
                    740: 
                    741:   In order to compile on Visual studio, time.h is now correct and time_t
                    742:   and tm struct should be used. difftime should be used but sometimes I
                    743:   just make the differences in raw time format (time(&now).
                    744:   Trying to suppress #ifdef LINUX
                    745:   Add xdg-open for __linux in order to open default browser.
                    746: 
1.157     brouard   747:   Revision 1.156  2014/08/25 20:10:10  brouard
                    748:   *** empty log message ***
                    749: 
1.156     brouard   750:   Revision 1.155  2014/08/25 18:32:34  brouard
                    751:   Summary: New compile, minor changes
                    752:   Author: Brouard
                    753: 
1.155     brouard   754:   Revision 1.154  2014/06/20 17:32:08  brouard
                    755:   Summary: Outputs now all graphs of convergence to period prevalence
                    756: 
1.154     brouard   757:   Revision 1.153  2014/06/20 16:45:46  brouard
                    758:   Summary: If 3 live state, convergence to period prevalence on same graph
                    759:   Author: Brouard
                    760: 
1.153     brouard   761:   Revision 1.152  2014/06/18 17:54:09  brouard
                    762:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    763: 
1.152     brouard   764:   Revision 1.151  2014/06/18 16:43:30  brouard
                    765:   *** empty log message ***
                    766: 
1.151     brouard   767:   Revision 1.150  2014/06/18 16:42:35  brouard
                    768:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    769:   Author: brouard
                    770: 
1.150     brouard   771:   Revision 1.149  2014/06/18 15:51:14  brouard
                    772:   Summary: Some fixes in parameter files errors
                    773:   Author: Nicolas Brouard
                    774: 
1.149     brouard   775:   Revision 1.148  2014/06/17 17:38:48  brouard
                    776:   Summary: Nothing new
                    777:   Author: Brouard
                    778: 
                    779:   Just a new packaging for OS/X version 0.98nS
                    780: 
1.148     brouard   781:   Revision 1.147  2014/06/16 10:33:11  brouard
                    782:   *** empty log message ***
                    783: 
1.147     brouard   784:   Revision 1.146  2014/06/16 10:20:28  brouard
                    785:   Summary: Merge
                    786:   Author: Brouard
                    787: 
                    788:   Merge, before building revised version.
                    789: 
1.146     brouard   790:   Revision 1.145  2014/06/10 21:23:15  brouard
                    791:   Summary: Debugging with valgrind
                    792:   Author: Nicolas Brouard
                    793: 
                    794:   Lot of changes in order to output the results with some covariates
                    795:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    796:   improve the code.
                    797:   No more memory valgrind error but a lot has to be done in order to
                    798:   continue the work of splitting the code into subroutines.
                    799:   Also, decodemodel has been improved. Tricode is still not
                    800:   optimal. nbcode should be improved. Documentation has been added in
                    801:   the source code.
                    802: 
1.144     brouard   803:   Revision 1.143  2014/01/26 09:45:38  brouard
                    804:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    805: 
                    806:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    807:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    808: 
1.143     brouard   809:   Revision 1.142  2014/01/26 03:57:36  brouard
                    810:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    811: 
                    812:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    813: 
1.142     brouard   814:   Revision 1.141  2014/01/26 02:42:01  brouard
                    815:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    816: 
1.141     brouard   817:   Revision 1.140  2011/09/02 10:37:54  brouard
                    818:   Summary: times.h is ok with mingw32 now.
                    819: 
1.140     brouard   820:   Revision 1.139  2010/06/14 07:50:17  brouard
                    821:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    822:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    823: 
1.139     brouard   824:   Revision 1.138  2010/04/30 18:19:40  brouard
                    825:   *** empty log message ***
                    826: 
1.138     brouard   827:   Revision 1.137  2010/04/29 18:11:38  brouard
                    828:   (Module): Checking covariates for more complex models
                    829:   than V1+V2. A lot of change to be done. Unstable.
                    830: 
1.137     brouard   831:   Revision 1.136  2010/04/26 20:30:53  brouard
                    832:   (Module): merging some libgsl code. Fixing computation
                    833:   of likelione (using inter/intrapolation if mle = 0) in order to
                    834:   get same likelihood as if mle=1.
                    835:   Some cleaning of code and comments added.
                    836: 
1.136     brouard   837:   Revision 1.135  2009/10/29 15:33:14  brouard
                    838:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    839: 
1.135     brouard   840:   Revision 1.134  2009/10/29 13:18:53  brouard
                    841:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    842: 
1.134     brouard   843:   Revision 1.133  2009/07/06 10:21:25  brouard
                    844:   just nforces
                    845: 
1.133     brouard   846:   Revision 1.132  2009/07/06 08:22:05  brouard
                    847:   Many tings
                    848: 
1.132     brouard   849:   Revision 1.131  2009/06/20 16:22:47  brouard
                    850:   Some dimensions resccaled
                    851: 
1.131     brouard   852:   Revision 1.130  2009/05/26 06:44:34  brouard
                    853:   (Module): Max Covariate is now set to 20 instead of 8. A
                    854:   lot of cleaning with variables initialized to 0. Trying to make
                    855:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    856: 
1.130     brouard   857:   Revision 1.129  2007/08/31 13:49:27  lievre
                    858:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    859: 
1.129     lievre    860:   Revision 1.128  2006/06/30 13:02:05  brouard
                    861:   (Module): Clarifications on computing e.j
                    862: 
1.128     brouard   863:   Revision 1.127  2006/04/28 18:11:50  brouard
                    864:   (Module): Yes the sum of survivors was wrong since
                    865:   imach-114 because nhstepm was no more computed in the age
                    866:   loop. Now we define nhstepma in the age loop.
                    867:   (Module): In order to speed up (in case of numerous covariates) we
                    868:   compute health expectancies (without variances) in a first step
                    869:   and then all the health expectancies with variances or standard
                    870:   deviation (needs data from the Hessian matrices) which slows the
                    871:   computation.
                    872:   In the future we should be able to stop the program is only health
                    873:   expectancies and graph are needed without standard deviations.
                    874: 
1.127     brouard   875:   Revision 1.126  2006/04/28 17:23:28  brouard
                    876:   (Module): Yes the sum of survivors was wrong since
                    877:   imach-114 because nhstepm was no more computed in the age
                    878:   loop. Now we define nhstepma in the age loop.
                    879:   Version 0.98h
                    880: 
1.126     brouard   881:   Revision 1.125  2006/04/04 15:20:31  lievre
                    882:   Errors in calculation of health expectancies. Age was not initialized.
                    883:   Forecasting file added.
                    884: 
                    885:   Revision 1.124  2006/03/22 17:13:53  lievre
                    886:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    887:   The log-likelihood is printed in the log file
                    888: 
                    889:   Revision 1.123  2006/03/20 10:52:43  brouard
                    890:   * imach.c (Module): <title> changed, corresponds to .htm file
                    891:   name. <head> headers where missing.
                    892: 
                    893:   * imach.c (Module): Weights can have a decimal point as for
                    894:   English (a comma might work with a correct LC_NUMERIC environment,
                    895:   otherwise the weight is truncated).
                    896:   Modification of warning when the covariates values are not 0 or
                    897:   1.
                    898:   Version 0.98g
                    899: 
                    900:   Revision 1.122  2006/03/20 09:45:41  brouard
                    901:   (Module): Weights can have a decimal point as for
                    902:   English (a comma might work with a correct LC_NUMERIC environment,
                    903:   otherwise the weight is truncated).
                    904:   Modification of warning when the covariates values are not 0 or
                    905:   1.
                    906:   Version 0.98g
                    907: 
                    908:   Revision 1.121  2006/03/16 17:45:01  lievre
                    909:   * imach.c (Module): Comments concerning covariates added
                    910: 
                    911:   * imach.c (Module): refinements in the computation of lli if
                    912:   status=-2 in order to have more reliable computation if stepm is
                    913:   not 1 month. Version 0.98f
                    914: 
                    915:   Revision 1.120  2006/03/16 15:10:38  lievre
                    916:   (Module): refinements in the computation of lli if
                    917:   status=-2 in order to have more reliable computation if stepm is
                    918:   not 1 month. Version 0.98f
                    919: 
                    920:   Revision 1.119  2006/03/15 17:42:26  brouard
                    921:   (Module): Bug if status = -2, the loglikelihood was
                    922:   computed as likelihood omitting the logarithm. Version O.98e
                    923: 
                    924:   Revision 1.118  2006/03/14 18:20:07  brouard
                    925:   (Module): varevsij Comments added explaining the second
                    926:   table of variances if popbased=1 .
                    927:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    928:   (Module): Function pstamp added
                    929:   (Module): Version 0.98d
                    930: 
                    931:   Revision 1.117  2006/03/14 17:16:22  brouard
                    932:   (Module): varevsij Comments added explaining the second
                    933:   table of variances if popbased=1 .
                    934:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    935:   (Module): Function pstamp added
                    936:   (Module): Version 0.98d
                    937: 
                    938:   Revision 1.116  2006/03/06 10:29:27  brouard
                    939:   (Module): Variance-covariance wrong links and
                    940:   varian-covariance of ej. is needed (Saito).
                    941: 
                    942:   Revision 1.115  2006/02/27 12:17:45  brouard
                    943:   (Module): One freematrix added in mlikeli! 0.98c
                    944: 
                    945:   Revision 1.114  2006/02/26 12:57:58  brouard
                    946:   (Module): Some improvements in processing parameter
                    947:   filename with strsep.
                    948: 
                    949:   Revision 1.113  2006/02/24 14:20:24  brouard
                    950:   (Module): Memory leaks checks with valgrind and:
                    951:   datafile was not closed, some imatrix were not freed and on matrix
                    952:   allocation too.
                    953: 
                    954:   Revision 1.112  2006/01/30 09:55:26  brouard
                    955:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    956: 
                    957:   Revision 1.111  2006/01/25 20:38:18  brouard
                    958:   (Module): Lots of cleaning and bugs added (Gompertz)
                    959:   (Module): Comments can be added in data file. Missing date values
                    960:   can be a simple dot '.'.
                    961: 
                    962:   Revision 1.110  2006/01/25 00:51:50  brouard
                    963:   (Module): Lots of cleaning and bugs added (Gompertz)
                    964: 
                    965:   Revision 1.109  2006/01/24 19:37:15  brouard
                    966:   (Module): Comments (lines starting with a #) are allowed in data.
                    967: 
                    968:   Revision 1.108  2006/01/19 18:05:42  lievre
                    969:   Gnuplot problem appeared...
                    970:   To be fixed
                    971: 
                    972:   Revision 1.107  2006/01/19 16:20:37  brouard
                    973:   Test existence of gnuplot in imach path
                    974: 
                    975:   Revision 1.106  2006/01/19 13:24:36  brouard
                    976:   Some cleaning and links added in html output
                    977: 
                    978:   Revision 1.105  2006/01/05 20:23:19  lievre
                    979:   *** empty log message ***
                    980: 
                    981:   Revision 1.104  2005/09/30 16:11:43  lievre
                    982:   (Module): sump fixed, loop imx fixed, and simplifications.
                    983:   (Module): If the status is missing at the last wave but we know
                    984:   that the person is alive, then we can code his/her status as -2
                    985:   (instead of missing=-1 in earlier versions) and his/her
                    986:   contributions to the likelihood is 1 - Prob of dying from last
                    987:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    988:   the healthy state at last known wave). Version is 0.98
                    989: 
                    990:   Revision 1.103  2005/09/30 15:54:49  lievre
                    991:   (Module): sump fixed, loop imx fixed, and simplifications.
                    992: 
                    993:   Revision 1.102  2004/09/15 17:31:30  brouard
                    994:   Add the possibility to read data file including tab characters.
                    995: 
                    996:   Revision 1.101  2004/09/15 10:38:38  brouard
                    997:   Fix on curr_time
                    998: 
                    999:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1000:   Add version for Mac OS X. Just define UNIX in Makefile
                   1001: 
                   1002:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1003:   *** empty log message ***
                   1004: 
                   1005:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1006:   New version 0.97 . First attempt to estimate force of mortality
                   1007:   directly from the data i.e. without the need of knowing the health
                   1008:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1009:   This is the basic analysis of mortality and should be done before any
                   1010:   other analysis, in order to test if the mortality estimated from the
                   1011:   cross-longitudinal survey is different from the mortality estimated
                   1012:   from other sources like vital statistic data.
                   1013: 
                   1014:   The same imach parameter file can be used but the option for mle should be -3.
                   1015: 
1.324     brouard  1016:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1017:   former routines in order to include the new code within the former code.
                   1018: 
                   1019:   The output is very simple: only an estimate of the intercept and of
                   1020:   the slope with 95% confident intervals.
                   1021: 
                   1022:   Current limitations:
                   1023:   A) Even if you enter covariates, i.e. with the
                   1024:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1025:   B) There is no computation of Life Expectancy nor Life Table.
                   1026: 
                   1027:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1028:   Version 0.96d. Population forecasting command line is (temporarily)
                   1029:   suppressed.
                   1030: 
                   1031:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1032:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1033:   rewritten within the same printf. Workaround: many printfs.
                   1034: 
                   1035:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1036:   * imach.c (Repository):
                   1037:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1038:   matrix (cov(a12,c31) instead of numbers.
                   1039: 
                   1040:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1041:   Just cleaning
                   1042: 
                   1043:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1044:   (Module): On windows (cygwin) function asctime_r doesn't
                   1045:   exist so I changed back to asctime which exists.
                   1046:   (Module): Version 0.96b
                   1047: 
                   1048:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1049:   (Module): On windows (cygwin) function asctime_r doesn't
                   1050:   exist so I changed back to asctime which exists.
                   1051: 
                   1052:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1053:   * imach.c (Repository): Duplicated warning errors corrected.
                   1054:   (Repository): Elapsed time after each iteration is now output. It
                   1055:   helps to forecast when convergence will be reached. Elapsed time
                   1056:   is stamped in powell.  We created a new html file for the graphs
                   1057:   concerning matrix of covariance. It has extension -cov.htm.
                   1058: 
                   1059:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1060:   (Module): Some bugs corrected for windows. Also, when
                   1061:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1062:   of the covariance matrix to be input.
                   1063: 
                   1064:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1065:   (Module): Some bugs corrected for windows. Also, when
                   1066:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1067:   of the covariance matrix to be input.
                   1068: 
                   1069:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1070:   * 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.
                   1071: 
                   1072:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1073:   Version 0.96
                   1074: 
                   1075:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1076:   (Module): Change position of html and gnuplot routines and added
                   1077:   routine fileappend.
                   1078: 
                   1079:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1080:   * imach.c (Repository): Check when date of death was earlier that
                   1081:   current date of interview. It may happen when the death was just
                   1082:   prior to the death. In this case, dh was negative and likelihood
                   1083:   was wrong (infinity). We still send an "Error" but patch by
                   1084:   assuming that the date of death was just one stepm after the
                   1085:   interview.
                   1086:   (Repository): Because some people have very long ID (first column)
                   1087:   we changed int to long in num[] and we added a new lvector for
                   1088:   memory allocation. But we also truncated to 8 characters (left
                   1089:   truncation)
                   1090:   (Repository): No more line truncation errors.
                   1091: 
                   1092:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1093:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1094:   place. It differs from routine "prevalence" which may be called
                   1095:   many times. Probs is memory consuming and must be used with
                   1096:   parcimony.
                   1097:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1098: 
                   1099:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1100:   *** empty log message ***
                   1101: 
                   1102:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1103:   Add log in  imach.c and  fullversion number is now printed.
                   1104: 
                   1105: */
                   1106: /*
                   1107:    Interpolated Markov Chain
                   1108: 
                   1109:   Short summary of the programme:
                   1110:   
1.227     brouard  1111:   This program computes Healthy Life Expectancies or State-specific
                   1112:   (if states aren't health statuses) Expectancies from
                   1113:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1114: 
                   1115:   -1- a first survey ("cross") where individuals from different ages
                   1116:   are interviewed on their health status or degree of disability (in
                   1117:   the case of a health survey which is our main interest)
                   1118: 
                   1119:   -2- at least a second wave of interviews ("longitudinal") which
                   1120:   measure each change (if any) in individual health status.  Health
                   1121:   expectancies are computed from the time spent in each health state
                   1122:   according to a model. More health states you consider, more time is
                   1123:   necessary to reach the Maximum Likelihood of the parameters involved
                   1124:   in the model.  The simplest model is the multinomial logistic model
                   1125:   where pij is the probability to be observed in state j at the second
                   1126:   wave conditional to be observed in state i at the first
                   1127:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1128:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1129:   have a more complex model than "constant and age", you should modify
                   1130:   the program where the markup *Covariates have to be included here
                   1131:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1132:   convergence.
                   1133: 
                   1134:   The advantage of this computer programme, compared to a simple
                   1135:   multinomial logistic model, is clear when the delay between waves is not
                   1136:   identical for each individual. Also, if a individual missed an
                   1137:   intermediate interview, the information is lost, but taken into
                   1138:   account using an interpolation or extrapolation.  
                   1139: 
                   1140:   hPijx is the probability to be observed in state i at age x+h
                   1141:   conditional to the observed state i at age x. The delay 'h' can be
                   1142:   split into an exact number (nh*stepm) of unobserved intermediate
                   1143:   states. This elementary transition (by month, quarter,
                   1144:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1145:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1146:   and the contribution of each individual to the likelihood is simply
                   1147:   hPijx.
                   1148: 
                   1149:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1150:   of the life expectancies. It also computes the period (stable) prevalence.
                   1151: 
                   1152: Back prevalence and projections:
1.227     brouard  1153: 
                   1154:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1155:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1156:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1157:    mobilavproj)
                   1158: 
                   1159:     Computes the back prevalence limit for any combination of
                   1160:     covariate values k at any age between ageminpar and agemaxpar and
                   1161:     returns it in **bprlim. In the loops,
                   1162: 
                   1163:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1164:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1165: 
                   1166:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1167:    Computes for any combination of covariates k and any age between bage and fage 
                   1168:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1169:                        oldm=oldms;savm=savms;
1.227     brouard  1170: 
1.267     brouard  1171:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1172:      Computes the transition matrix starting at age 'age' over
                   1173:      'nhstepm*hstepm*stepm' months (i.e. until
                   1174:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1175:      nhstepm*hstepm matrices. 
                   1176: 
                   1177:      Returns p3mat[i][j][h] after calling
                   1178:      p3mat[i][j][h]=matprod2(newm,
                   1179:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1180:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1181:      oldm);
1.226     brouard  1182: 
                   1183: Important routines
                   1184: 
                   1185: - func (or funcone), computes logit (pij) distinguishing
                   1186:   o fixed variables (single or product dummies or quantitative);
                   1187:   o varying variables by:
                   1188:    (1) wave (single, product dummies, quantitative), 
                   1189:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1190:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1191:        % varying dummy (not done) or quantitative (not done);
                   1192: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1193:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1194: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1195:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1196:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1197: 
1.226     brouard  1198: 
                   1199:   
1.324     brouard  1200:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1201:            Institut national d'études démographiques, Paris.
1.126     brouard  1202:   This software have been partly granted by Euro-REVES, a concerted action
                   1203:   from the European Union.
                   1204:   It is copyrighted identically to a GNU software product, ie programme and
                   1205:   software can be distributed freely for non commercial use. Latest version
                   1206:   can be accessed at http://euroreves.ined.fr/imach .
                   1207: 
                   1208:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1209:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1210:   
                   1211:   **********************************************************************/
                   1212: /*
                   1213:   main
                   1214:   read parameterfile
                   1215:   read datafile
                   1216:   concatwav
                   1217:   freqsummary
                   1218:   if (mle >= 1)
                   1219:     mlikeli
                   1220:   print results files
                   1221:   if mle==1 
                   1222:      computes hessian
                   1223:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1224:       begin-prev-date,...
                   1225:   open gnuplot file
                   1226:   open html file
1.145     brouard  1227:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1228:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1229:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1230:     freexexit2 possible for memory heap.
                   1231: 
                   1232:   h Pij x                         | pij_nom  ficrestpij
                   1233:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1234:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1235:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1236: 
                   1237:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1238:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1239:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1240:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1241:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1242: 
1.126     brouard  1243:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1244:   health expectancies
                   1245:   Variance-covariance of DFLE
                   1246:   prevalence()
                   1247:    movingaverage()
                   1248:   varevsij() 
                   1249:   if popbased==1 varevsij(,popbased)
                   1250:   total life expectancies
                   1251:   Variance of period (stable) prevalence
                   1252:  end
                   1253: */
                   1254: 
1.187     brouard  1255: /* #define DEBUG */
                   1256: /* #define DEBUGBRENT */
1.203     brouard  1257: /* #define DEBUGLINMIN */
                   1258: /* #define DEBUGHESS */
                   1259: #define DEBUGHESSIJ
1.224     brouard  1260: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1261: #define POWELL /* Instead of NLOPT */
1.224     brouard  1262: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1263: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1264: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1265: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1266: 
                   1267: #include <math.h>
                   1268: #include <stdio.h>
                   1269: #include <stdlib.h>
                   1270: #include <string.h>
1.226     brouard  1271: #include <ctype.h>
1.159     brouard  1272: 
                   1273: #ifdef _WIN32
                   1274: #include <io.h>
1.172     brouard  1275: #include <windows.h>
                   1276: #include <tchar.h>
1.159     brouard  1277: #else
1.126     brouard  1278: #include <unistd.h>
1.159     brouard  1279: #endif
1.126     brouard  1280: 
                   1281: #include <limits.h>
                   1282: #include <sys/types.h>
1.171     brouard  1283: 
                   1284: #if defined(__GNUC__)
                   1285: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1286: #endif
                   1287: 
1.126     brouard  1288: #include <sys/stat.h>
                   1289: #include <errno.h>
1.159     brouard  1290: /* extern int errno; */
1.126     brouard  1291: 
1.157     brouard  1292: /* #ifdef LINUX */
                   1293: /* #include <time.h> */
                   1294: /* #include "timeval.h" */
                   1295: /* #else */
                   1296: /* #include <sys/time.h> */
                   1297: /* #endif */
                   1298: 
1.126     brouard  1299: #include <time.h>
                   1300: 
1.136     brouard  1301: #ifdef GSL
                   1302: #include <gsl/gsl_errno.h>
                   1303: #include <gsl/gsl_multimin.h>
                   1304: #endif
                   1305: 
1.167     brouard  1306: 
1.162     brouard  1307: #ifdef NLOPT
                   1308: #include <nlopt.h>
                   1309: typedef struct {
                   1310:   double (* function)(double [] );
                   1311: } myfunc_data ;
                   1312: #endif
                   1313: 
1.126     brouard  1314: /* #include <libintl.h> */
                   1315: /* #define _(String) gettext (String) */
                   1316: 
1.251     brouard  1317: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1318: 
                   1319: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1320: #define GNUPLOTVERSION 5.1
                   1321: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1322: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1323: #define FILENAMELENGTH 256
1.126     brouard  1324: 
                   1325: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1326: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1327: 
1.144     brouard  1328: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1329: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1330: 
                   1331: #define NINTERVMAX 8
1.144     brouard  1332: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1333: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1334: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1335: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1336: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1337: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1338: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1339: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1340: /* #define AGESUP 130 */
1.288     brouard  1341: /* #define AGESUP 150 */
                   1342: #define AGESUP 200
1.268     brouard  1343: #define AGEINF 0
1.218     brouard  1344: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1345: #define AGEBASE 40
1.194     brouard  1346: #define AGEOVERFLOW 1.e20
1.164     brouard  1347: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1348: #ifdef _WIN32
                   1349: #define DIRSEPARATOR '\\'
                   1350: #define CHARSEPARATOR "\\"
                   1351: #define ODIRSEPARATOR '/'
                   1352: #else
1.126     brouard  1353: #define DIRSEPARATOR '/'
                   1354: #define CHARSEPARATOR "/"
                   1355: #define ODIRSEPARATOR '\\'
                   1356: #endif
                   1357: 
1.348   ! brouard  1358: /* $Id: imach.c,v 1.347 2022/09/18 14:36:44 brouard Exp $ */
1.126     brouard  1359: /* $State: Exp $ */
1.196     brouard  1360: #include "version.h"
                   1361: char version[]=__IMACH_VERSION__;
1.337     brouard  1362: char copyright[]="September 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.348   ! brouard  1363: char fullversion[]="$Revision: 1.347 $ $Date: 2022/09/18 14:36:44 $"; 
1.126     brouard  1364: char strstart[80];
                   1365: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1366: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1367: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1368: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1369: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1370: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1371: 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  1372: 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  1373: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1374: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1375: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1376: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1377: 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  1378: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1379: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1380: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1381: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1382: int nsd=0; /**< Total number of single dummy variables (output) */
                   1383: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1384: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1385: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1386: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1387: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1388: int cptcov=0; /* Working variable */
1.334     brouard  1389: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1390: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1391: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1392: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1393: int nlstate=2; /* Number of live states */
                   1394: int ndeath=1; /* Number of dead states */
1.130     brouard  1395: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1396: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1397: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1398: int popbased=0;
                   1399: 
                   1400: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1401: int maxwav=0; /* Maxim number of waves */
                   1402: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1403: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1404: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1405:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1406: int mle=1, weightopt=0;
1.126     brouard  1407: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1408: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1409: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1410:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1411: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1412: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1413: 
1.130     brouard  1414: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1415: double **matprod2(); /* test */
1.126     brouard  1416: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1417: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1418: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1419: 
1.136     brouard  1420: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1421: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1422: FILE *ficlog, *ficrespow;
1.130     brouard  1423: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1424: double fretone; /* Only one call to likelihood */
1.130     brouard  1425: long ipmx=0; /* Number of contributions */
1.126     brouard  1426: double sw; /* Sum of weights */
                   1427: char filerespow[FILENAMELENGTH];
                   1428: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1429: FILE *ficresilk;
                   1430: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1431: FILE *ficresprobmorprev;
                   1432: FILE *fichtm, *fichtmcov; /* Html File */
                   1433: FILE *ficreseij;
                   1434: char filerese[FILENAMELENGTH];
                   1435: FILE *ficresstdeij;
                   1436: char fileresstde[FILENAMELENGTH];
                   1437: FILE *ficrescveij;
                   1438: char filerescve[FILENAMELENGTH];
                   1439: FILE  *ficresvij;
                   1440: char fileresv[FILENAMELENGTH];
1.269     brouard  1441: 
1.126     brouard  1442: char title[MAXLINE];
1.234     brouard  1443: char model[MAXLINE]; /**< The model line */
1.217     brouard  1444: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1445: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1446: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1447: char command[FILENAMELENGTH];
                   1448: int  outcmd=0;
                   1449: 
1.217     brouard  1450: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1451: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1452: char filelog[FILENAMELENGTH]; /* Log file */
                   1453: char filerest[FILENAMELENGTH];
                   1454: char fileregp[FILENAMELENGTH];
                   1455: char popfile[FILENAMELENGTH];
                   1456: 
                   1457: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1458: 
1.157     brouard  1459: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1460: /* struct timezone tzp; */
                   1461: /* extern int gettimeofday(); */
                   1462: struct tm tml, *gmtime(), *localtime();
                   1463: 
                   1464: extern time_t time();
                   1465: 
                   1466: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1467: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1468: struct tm tm;
                   1469: 
1.126     brouard  1470: char strcurr[80], strfor[80];
                   1471: 
                   1472: char *endptr;
                   1473: long lval;
                   1474: double dval;
                   1475: 
                   1476: #define NR_END 1
                   1477: #define FREE_ARG char*
                   1478: #define FTOL 1.0e-10
                   1479: 
                   1480: #define NRANSI 
1.240     brouard  1481: #define ITMAX 200
                   1482: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1483: 
                   1484: #define TOL 2.0e-4 
                   1485: 
                   1486: #define CGOLD 0.3819660 
                   1487: #define ZEPS 1.0e-10 
                   1488: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1489: 
                   1490: #define GOLD 1.618034 
                   1491: #define GLIMIT 100.0 
                   1492: #define TINY 1.0e-20 
                   1493: 
                   1494: static double maxarg1,maxarg2;
                   1495: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1496: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1497:   
                   1498: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1499: #define rint(a) floor(a+0.5)
1.166     brouard  1500: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1501: #define mytinydouble 1.0e-16
1.166     brouard  1502: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1503: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1504: /* static double dsqrarg; */
                   1505: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1506: static double sqrarg;
                   1507: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1508: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1509: int agegomp= AGEGOMP;
                   1510: 
                   1511: int imx; 
                   1512: int stepm=1;
                   1513: /* Stepm, step in month: minimum step interpolation*/
                   1514: 
                   1515: int estepm;
                   1516: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1517: 
                   1518: int m,nb;
                   1519: long *num;
1.197     brouard  1520: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1521: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1522:                   covariate for which somebody answered excluding 
                   1523:                   undefined. Usually 2: 0 and 1. */
                   1524: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1525:                             covariate for which somebody answered including 
                   1526:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1527: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1528: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1529: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1530: 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  1531: double *ageexmed,*agecens;
                   1532: double dateintmean=0;
1.296     brouard  1533:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1534:   double anprojf, mprojf, jprojf;
1.126     brouard  1535: 
1.296     brouard  1536:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1537:   double anbackf, mbackf, jbackf;
                   1538:   double jintmean,mintmean,aintmean;  
1.126     brouard  1539: double *weight;
                   1540: int **s; /* Status */
1.141     brouard  1541: double *agedc;
1.145     brouard  1542: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1543:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1544:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1545: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1546: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1547: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1548: double  idx; 
                   1549: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1550: /* Some documentation */
                   1551:       /*   Design original data
                   1552:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1553:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1554:        *                                                             ntv=3     nqtv=1
1.330     brouard  1555:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1556:        * For time varying covariate, quanti or dummies
                   1557:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1558:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1559:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1560:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1561:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1562:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1563:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1564:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1565:        */
                   1566: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1567: /* 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
                   1568:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1569:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1570: */
1.343     brouard  1571: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
                   1572: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1573: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1574:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1575:                                                          /* product */
                   1576: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1577:                                                          /*(single or product without age), 2 dummy*/
                   1578:                                                          /* with age product, 3 quant with age product*/
                   1579: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1580: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1581: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1582: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1583: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1584: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1585: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1586: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1587: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1588: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1589: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1590: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1591: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1592: /* 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  1593: /* 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  1594: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1595: /* Type                    */
                   1596: /* V         1  2  3  4  5 */
                   1597: /*           F  F  V  V  V */
                   1598: /*           D  Q  D  D  Q */
                   1599: /*                         */
                   1600: int *TvarsD;
1.330     brouard  1601: int *TnsdVar;
1.234     brouard  1602: int *TvarsDind;
                   1603: int *TvarsQ;
                   1604: int *TvarsQind;
                   1605: 
1.318     brouard  1606: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1607: int nresult=0;
1.258     brouard  1608: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1609: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1610: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1611: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1612: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1613: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1614: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1615: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1616: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1617: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1618: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1619: 
                   1620: /* 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
                   1621:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1622:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1623: */
1.234     brouard  1624: /* 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  1625: 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 */
                   1626: 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 */
                   1627: 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 */
                   1628: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1629: 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 */
                   1630: 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  1631: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1632: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1633: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1634: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1635: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1636: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1637: 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 */
                   1638: 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 */
1.339     brouard  1639: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1640: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1641:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1642:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1643:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1644:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1645:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1646: int *Tvarsel; /**< Selected covariates for output */
                   1647: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1648: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1649: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1650: 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  1651: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1652: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1653: int *Tage;
1.227     brouard  1654: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1655: 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  1656: 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*/ 
                   1657: 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  1658: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1659: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1660: int **Tvard;
1.330     brouard  1661: int **Tvardk;
1.227     brouard  1662: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1663: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1664: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1665:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1666:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1667: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1668: double *lsurv, *lpop, *tpop;
                   1669: 
1.231     brouard  1670: #define FD 1; /* Fixed dummy covariate */
                   1671: #define FQ 2; /* Fixed quantitative covariate */
                   1672: #define FP 3; /* Fixed product covariate */
                   1673: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1674: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1675: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1676: #define VD 10; /* Varying dummy covariate */
                   1677: #define VQ 11; /* Varying quantitative covariate */
                   1678: #define VP 12; /* Varying product covariate */
                   1679: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1680: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1681: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1682: #define APFD 16; /* Age product * fixed dummy covariate */
                   1683: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1684: #define APVD 18; /* Age product * varying dummy covariate */
                   1685: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1686: 
                   1687: #define FTYPE 1; /* Fixed covariate */
                   1688: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1689: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1690: 
                   1691: struct kmodel{
                   1692:        int maintype; /* main type */
                   1693:        int subtype; /* subtype */
                   1694: };
                   1695: struct kmodel modell[NCOVMAX];
                   1696: 
1.143     brouard  1697: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1698: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1699: 
                   1700: /**************** split *************************/
                   1701: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1702: {
                   1703:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1704:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1705:   */ 
                   1706:   char *ss;                            /* pointer */
1.186     brouard  1707:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1708: 
                   1709:   l1 = strlen(path );                  /* length of path */
                   1710:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1711:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1712:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1713:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1714:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1715:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1716:     /* get current working directory */
                   1717:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1718: #ifdef WIN32
                   1719:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1720: #else
                   1721:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1722: #endif
1.126     brouard  1723:       return( GLOCK_ERROR_GETCWD );
                   1724:     }
                   1725:     /* got dirc from getcwd*/
                   1726:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1727:   } else {                             /* strip directory from path */
1.126     brouard  1728:     ss++;                              /* after this, the filename */
                   1729:     l2 = strlen( ss );                 /* length of filename */
                   1730:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1731:     strcpy( name, ss );                /* save file name */
                   1732:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1733:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1734:     printf(" DIRC2 = %s \n",dirc);
                   1735:   }
                   1736:   /* We add a separator at the end of dirc if not exists */
                   1737:   l1 = strlen( dirc );                 /* length of directory */
                   1738:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1739:     dirc[l1] =  DIRSEPARATOR;
                   1740:     dirc[l1+1] = 0; 
                   1741:     printf(" DIRC3 = %s \n",dirc);
                   1742:   }
                   1743:   ss = strrchr( name, '.' );           /* find last / */
                   1744:   if (ss >0){
                   1745:     ss++;
                   1746:     strcpy(ext,ss);                    /* save extension */
                   1747:     l1= strlen( name);
                   1748:     l2= strlen(ss)+1;
                   1749:     strncpy( finame, name, l1-l2);
                   1750:     finame[l1-l2]= 0;
                   1751:   }
                   1752: 
                   1753:   return( 0 );                         /* we're done */
                   1754: }
                   1755: 
                   1756: 
                   1757: /******************************************/
                   1758: 
                   1759: void replace_back_to_slash(char *s, char*t)
                   1760: {
                   1761:   int i;
                   1762:   int lg=0;
                   1763:   i=0;
                   1764:   lg=strlen(t);
                   1765:   for(i=0; i<= lg; i++) {
                   1766:     (s[i] = t[i]);
                   1767:     if (t[i]== '\\') s[i]='/';
                   1768:   }
                   1769: }
                   1770: 
1.132     brouard  1771: char *trimbb(char *out, char *in)
1.137     brouard  1772: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1773:   char *s;
                   1774:   s=out;
                   1775:   while (*in != '\0'){
1.137     brouard  1776:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1777:       in++;
                   1778:     }
                   1779:     *out++ = *in++;
                   1780:   }
                   1781:   *out='\0';
                   1782:   return s;
                   1783: }
                   1784: 
1.187     brouard  1785: /* char *substrchaine(char *out, char *in, char *chain) */
                   1786: /* { */
                   1787: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1788: /*   char *s, *t; */
                   1789: /*   t=in;s=out; */
                   1790: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1791: /*     *out++ = *in++; */
                   1792: /*   } */
                   1793: 
                   1794: /*   /\* *in matches *chain *\/ */
                   1795: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1796: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1797: /*   } */
                   1798: /*   in--; chain--; */
                   1799: /*   while ( (*in != '\0')){ */
                   1800: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1801: /*     *out++ = *in++; */
                   1802: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1803: /*   } */
                   1804: /*   *out='\0'; */
                   1805: /*   out=s; */
                   1806: /*   return out; */
                   1807: /* } */
                   1808: char *substrchaine(char *out, char *in, char *chain)
                   1809: {
                   1810:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1811:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1812: 
                   1813:   char *strloc;
                   1814: 
                   1815:   strcpy (out, in); 
                   1816:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1817:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1818:   if(strloc != NULL){ 
                   1819:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1820:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1821:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1822:   }
                   1823:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1824:   return out;
                   1825: }
                   1826: 
                   1827: 
1.145     brouard  1828: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1829: {
1.187     brouard  1830:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1831:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1832:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1833:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1834:   */
1.160     brouard  1835:   char *s, *t;
1.145     brouard  1836:   t=in;s=in;
                   1837:   while ((*in != occ) && (*in != '\0')){
                   1838:     *alocc++ = *in++;
                   1839:   }
                   1840:   if( *in == occ){
                   1841:     *(alocc)='\0';
                   1842:     s=++in;
                   1843:   }
                   1844:  
                   1845:   if (s == t) {/* occ not found */
                   1846:     *(alocc-(in-s))='\0';
                   1847:     in=s;
                   1848:   }
                   1849:   while ( *in != '\0'){
                   1850:     *blocc++ = *in++;
                   1851:   }
                   1852: 
                   1853:   *blocc='\0';
                   1854:   return t;
                   1855: }
1.137     brouard  1856: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1857: {
1.187     brouard  1858:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1859:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1860:      gives blocc="abcdef2ghi" and alocc="j".
                   1861:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1862:   */
                   1863:   char *s, *t;
                   1864:   t=in;s=in;
                   1865:   while (*in != '\0'){
                   1866:     while( *in == occ){
                   1867:       *blocc++ = *in++;
                   1868:       s=in;
                   1869:     }
                   1870:     *blocc++ = *in++;
                   1871:   }
                   1872:   if (s == t) /* occ not found */
                   1873:     *(blocc-(in-s))='\0';
                   1874:   else
                   1875:     *(blocc-(in-s)-1)='\0';
                   1876:   in=s;
                   1877:   while ( *in != '\0'){
                   1878:     *alocc++ = *in++;
                   1879:   }
                   1880: 
                   1881:   *alocc='\0';
                   1882:   return s;
                   1883: }
                   1884: 
1.126     brouard  1885: int nbocc(char *s, char occ)
                   1886: {
                   1887:   int i,j=0;
                   1888:   int lg=20;
                   1889:   i=0;
                   1890:   lg=strlen(s);
                   1891:   for(i=0; i<= lg; i++) {
1.234     brouard  1892:     if  (s[i] == occ ) j++;
1.126     brouard  1893:   }
                   1894:   return j;
                   1895: }
                   1896: 
1.137     brouard  1897: /* void cutv(char *u,char *v, char*t, char occ) */
                   1898: /* { */
                   1899: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1900: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1901: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1902: /*   int i,lg,j,p=0; */
                   1903: /*   i=0; */
                   1904: /*   lg=strlen(t); */
                   1905: /*   for(j=0; j<=lg-1; j++) { */
                   1906: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1907: /*   } */
1.126     brouard  1908: 
1.137     brouard  1909: /*   for(j=0; j<p; j++) { */
                   1910: /*     (u[j] = t[j]); */
                   1911: /*   } */
                   1912: /*      u[p]='\0'; */
1.126     brouard  1913: 
1.137     brouard  1914: /*    for(j=0; j<= lg; j++) { */
                   1915: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1916: /*   } */
                   1917: /* } */
1.126     brouard  1918: 
1.160     brouard  1919: #ifdef _WIN32
                   1920: char * strsep(char **pp, const char *delim)
                   1921: {
                   1922:   char *p, *q;
                   1923:          
                   1924:   if ((p = *pp) == NULL)
                   1925:     return 0;
                   1926:   if ((q = strpbrk (p, delim)) != NULL)
                   1927:   {
                   1928:     *pp = q + 1;
                   1929:     *q = '\0';
                   1930:   }
                   1931:   else
                   1932:     *pp = 0;
                   1933:   return p;
                   1934: }
                   1935: #endif
                   1936: 
1.126     brouard  1937: /********************** nrerror ********************/
                   1938: 
                   1939: void nrerror(char error_text[])
                   1940: {
                   1941:   fprintf(stderr,"ERREUR ...\n");
                   1942:   fprintf(stderr,"%s\n",error_text);
                   1943:   exit(EXIT_FAILURE);
                   1944: }
                   1945: /*********************** vector *******************/
                   1946: double *vector(int nl, int nh)
                   1947: {
                   1948:   double *v;
                   1949:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1950:   if (!v) nrerror("allocation failure in vector");
                   1951:   return v-nl+NR_END;
                   1952: }
                   1953: 
                   1954: /************************ free vector ******************/
                   1955: void free_vector(double*v, int nl, int nh)
                   1956: {
                   1957:   free((FREE_ARG)(v+nl-NR_END));
                   1958: }
                   1959: 
                   1960: /************************ivector *******************************/
                   1961: int *ivector(long nl,long nh)
                   1962: {
                   1963:   int *v;
                   1964:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1965:   if (!v) nrerror("allocation failure in ivector");
                   1966:   return v-nl+NR_END;
                   1967: }
                   1968: 
                   1969: /******************free ivector **************************/
                   1970: void free_ivector(int *v, long nl, long nh)
                   1971: {
                   1972:   free((FREE_ARG)(v+nl-NR_END));
                   1973: }
                   1974: 
                   1975: /************************lvector *******************************/
                   1976: long *lvector(long nl,long nh)
                   1977: {
                   1978:   long *v;
                   1979:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1980:   if (!v) nrerror("allocation failure in ivector");
                   1981:   return v-nl+NR_END;
                   1982: }
                   1983: 
                   1984: /******************free lvector **************************/
                   1985: void free_lvector(long *v, long nl, long nh)
                   1986: {
                   1987:   free((FREE_ARG)(v+nl-NR_END));
                   1988: }
                   1989: 
                   1990: /******************* imatrix *******************************/
                   1991: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1992:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1993: { 
                   1994:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1995:   int **m; 
                   1996:   
                   1997:   /* allocate pointers to rows */ 
                   1998:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1999:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2000:   m += NR_END; 
                   2001:   m -= nrl; 
                   2002:   
                   2003:   
                   2004:   /* allocate rows and set pointers to them */ 
                   2005:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2006:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2007:   m[nrl] += NR_END; 
                   2008:   m[nrl] -= ncl; 
                   2009:   
                   2010:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2011:   
                   2012:   /* return pointer to array of pointers to rows */ 
                   2013:   return m; 
                   2014: } 
                   2015: 
                   2016: /****************** free_imatrix *************************/
                   2017: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2018:       int **m;
                   2019:       long nch,ncl,nrh,nrl; 
                   2020:      /* free an int matrix allocated by imatrix() */ 
                   2021: { 
                   2022:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2023:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2024: } 
                   2025: 
                   2026: /******************* matrix *******************************/
                   2027: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2028: {
                   2029:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2030:   double **m;
                   2031: 
                   2032:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2033:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2034:   m += NR_END;
                   2035:   m -= nrl;
                   2036: 
                   2037:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2038:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2039:   m[nrl] += NR_END;
                   2040:   m[nrl] -= ncl;
                   2041: 
                   2042:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2043:   return m;
1.145     brouard  2044:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2045: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2046: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2047:    */
                   2048: }
                   2049: 
                   2050: /*************************free matrix ************************/
                   2051: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2052: {
                   2053:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2054:   free((FREE_ARG)(m+nrl-NR_END));
                   2055: }
                   2056: 
                   2057: /******************* ma3x *******************************/
                   2058: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2059: {
                   2060:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2061:   double ***m;
                   2062: 
                   2063:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2064:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2065:   m += NR_END;
                   2066:   m -= nrl;
                   2067: 
                   2068:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2069:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2070:   m[nrl] += NR_END;
                   2071:   m[nrl] -= ncl;
                   2072: 
                   2073:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2074: 
                   2075:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2076:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2077:   m[nrl][ncl] += NR_END;
                   2078:   m[nrl][ncl] -= nll;
                   2079:   for (j=ncl+1; j<=nch; j++) 
                   2080:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2081:   
                   2082:   for (i=nrl+1; i<=nrh; i++) {
                   2083:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2084:     for (j=ncl+1; j<=nch; j++) 
                   2085:       m[i][j]=m[i][j-1]+nlay;
                   2086:   }
                   2087:   return m; 
                   2088:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2089:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2090:   */
                   2091: }
                   2092: 
                   2093: /*************************free ma3x ************************/
                   2094: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2095: {
                   2096:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2097:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2098:   free((FREE_ARG)(m+nrl-NR_END));
                   2099: }
                   2100: 
                   2101: /*************** function subdirf ***********/
                   2102: char *subdirf(char fileres[])
                   2103: {
                   2104:   /* Caution optionfilefiname is hidden */
                   2105:   strcpy(tmpout,optionfilefiname);
                   2106:   strcat(tmpout,"/"); /* Add to the right */
                   2107:   strcat(tmpout,fileres);
                   2108:   return tmpout;
                   2109: }
                   2110: 
                   2111: /*************** function subdirf2 ***********/
                   2112: char *subdirf2(char fileres[], char *preop)
                   2113: {
1.314     brouard  2114:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2115:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2116:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2117:   /* Caution optionfilefiname is hidden */
                   2118:   strcpy(tmpout,optionfilefiname);
                   2119:   strcat(tmpout,"/");
                   2120:   strcat(tmpout,preop);
                   2121:   strcat(tmpout,fileres);
                   2122:   return tmpout;
                   2123: }
                   2124: 
                   2125: /*************** function subdirf3 ***********/
                   2126: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2127: {
                   2128:   
                   2129:   /* Caution optionfilefiname is hidden */
                   2130:   strcpy(tmpout,optionfilefiname);
                   2131:   strcat(tmpout,"/");
                   2132:   strcat(tmpout,preop);
                   2133:   strcat(tmpout,preop2);
                   2134:   strcat(tmpout,fileres);
                   2135:   return tmpout;
                   2136: }
1.213     brouard  2137:  
                   2138: /*************** function subdirfext ***********/
                   2139: char *subdirfext(char fileres[], char *preop, char *postop)
                   2140: {
                   2141:   
                   2142:   strcpy(tmpout,preop);
                   2143:   strcat(tmpout,fileres);
                   2144:   strcat(tmpout,postop);
                   2145:   return tmpout;
                   2146: }
1.126     brouard  2147: 
1.213     brouard  2148: /*************** function subdirfext3 ***********/
                   2149: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2150: {
                   2151:   
                   2152:   /* Caution optionfilefiname is hidden */
                   2153:   strcpy(tmpout,optionfilefiname);
                   2154:   strcat(tmpout,"/");
                   2155:   strcat(tmpout,preop);
                   2156:   strcat(tmpout,fileres);
                   2157:   strcat(tmpout,postop);
                   2158:   return tmpout;
                   2159: }
                   2160:  
1.162     brouard  2161: char *asc_diff_time(long time_sec, char ascdiff[])
                   2162: {
                   2163:   long sec_left, days, hours, minutes;
                   2164:   days = (time_sec) / (60*60*24);
                   2165:   sec_left = (time_sec) % (60*60*24);
                   2166:   hours = (sec_left) / (60*60) ;
                   2167:   sec_left = (sec_left) %(60*60);
                   2168:   minutes = (sec_left) /60;
                   2169:   sec_left = (sec_left) % (60);
                   2170:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2171:   return ascdiff;
                   2172: }
                   2173: 
1.126     brouard  2174: /***************** f1dim *************************/
                   2175: extern int ncom; 
                   2176: extern double *pcom,*xicom;
                   2177: extern double (*nrfunc)(double []); 
                   2178:  
                   2179: double f1dim(double x) 
                   2180: { 
                   2181:   int j; 
                   2182:   double f;
                   2183:   double *xt; 
                   2184:  
                   2185:   xt=vector(1,ncom); 
                   2186:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2187:   f=(*nrfunc)(xt); 
                   2188:   free_vector(xt,1,ncom); 
                   2189:   return f; 
                   2190: } 
                   2191: 
                   2192: /*****************brent *************************/
                   2193: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2194: {
                   2195:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2196:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2197:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2198:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2199:    * returned function value. 
                   2200:   */
1.126     brouard  2201:   int iter; 
                   2202:   double a,b,d,etemp;
1.159     brouard  2203:   double fu=0,fv,fw,fx;
1.164     brouard  2204:   double ftemp=0.;
1.126     brouard  2205:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2206:   double e=0.0; 
                   2207:  
                   2208:   a=(ax < cx ? ax : cx); 
                   2209:   b=(ax > cx ? ax : cx); 
                   2210:   x=w=v=bx; 
                   2211:   fw=fv=fx=(*f)(x); 
                   2212:   for (iter=1;iter<=ITMAX;iter++) { 
                   2213:     xm=0.5*(a+b); 
                   2214:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2215:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2216:     printf(".");fflush(stdout);
                   2217:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2218: #ifdef DEBUGBRENT
1.126     brouard  2219:     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);
                   2220:     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);
                   2221:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2222: #endif
                   2223:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2224:       *xmin=x; 
                   2225:       return fx; 
                   2226:     } 
                   2227:     ftemp=fu;
                   2228:     if (fabs(e) > tol1) { 
                   2229:       r=(x-w)*(fx-fv); 
                   2230:       q=(x-v)*(fx-fw); 
                   2231:       p=(x-v)*q-(x-w)*r; 
                   2232:       q=2.0*(q-r); 
                   2233:       if (q > 0.0) p = -p; 
                   2234:       q=fabs(q); 
                   2235:       etemp=e; 
                   2236:       e=d; 
                   2237:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2238:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2239:       else { 
1.224     brouard  2240:                                d=p/q; 
                   2241:                                u=x+d; 
                   2242:                                if (u-a < tol2 || b-u < tol2) 
                   2243:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2244:       } 
                   2245:     } else { 
                   2246:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2247:     } 
                   2248:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2249:     fu=(*f)(u); 
                   2250:     if (fu <= fx) { 
                   2251:       if (u >= x) a=x; else b=x; 
                   2252:       SHFT(v,w,x,u) 
1.183     brouard  2253:       SHFT(fv,fw,fx,fu) 
                   2254:     } else { 
                   2255:       if (u < x) a=u; else b=u; 
                   2256:       if (fu <= fw || w == x) { 
1.224     brouard  2257:                                v=w; 
                   2258:                                w=u; 
                   2259:                                fv=fw; 
                   2260:                                fw=fu; 
1.183     brouard  2261:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2262:                                v=u; 
                   2263:                                fv=fu; 
1.183     brouard  2264:       } 
                   2265:     } 
1.126     brouard  2266:   } 
                   2267:   nrerror("Too many iterations in brent"); 
                   2268:   *xmin=x; 
                   2269:   return fx; 
                   2270: } 
                   2271: 
                   2272: /****************** mnbrak ***********************/
                   2273: 
                   2274: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2275:            double (*func)(double)) 
1.183     brouard  2276: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2277: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2278: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2279: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2280:    */
1.126     brouard  2281:   double ulim,u,r,q, dum;
                   2282:   double fu; 
1.187     brouard  2283: 
                   2284:   double scale=10.;
                   2285:   int iterscale=0;
                   2286: 
                   2287:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2288:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2289: 
                   2290: 
                   2291:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2292:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2293:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2294:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2295:   /* } */
                   2296: 
1.126     brouard  2297:   if (*fb > *fa) { 
                   2298:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2299:     SHFT(dum,*fb,*fa,dum) 
                   2300:   } 
1.126     brouard  2301:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2302:   *fc=(*func)(*cx); 
1.183     brouard  2303: #ifdef DEBUG
1.224     brouard  2304:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2305:   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  2306: #endif
1.224     brouard  2307:   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  2308:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2309:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2310:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2311:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2312:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2313:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2314:       fu=(*func)(u); 
1.163     brouard  2315: #ifdef DEBUG
                   2316:       /* f(x)=A(x-u)**2+f(u) */
                   2317:       double A, fparabu; 
                   2318:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2319:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2320:       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);
                   2321:       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  2322:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2323:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2324:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2325:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2326: #endif 
1.184     brouard  2327: #ifdef MNBRAKORIGINAL
1.183     brouard  2328: #else
1.191     brouard  2329: /*       if (fu > *fc) { */
                   2330: /* #ifdef DEBUG */
                   2331: /*       printf("mnbrak4  fu > fc \n"); */
                   2332: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2333: /* #endif */
                   2334: /*     /\* 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 *\\/  *\/ */
                   2335: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2336: /*     dum=u; /\* Shifting c and u *\/ */
                   2337: /*     u = *cx; */
                   2338: /*     *cx = dum; */
                   2339: /*     dum = fu; */
                   2340: /*     fu = *fc; */
                   2341: /*     *fc =dum; */
                   2342: /*       } else { /\* end *\/ */
                   2343: /* #ifdef DEBUG */
                   2344: /*       printf("mnbrak3  fu < fc \n"); */
                   2345: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2346: /* #endif */
                   2347: /*     dum=u; /\* Shifting c and u *\/ */
                   2348: /*     u = *cx; */
                   2349: /*     *cx = dum; */
                   2350: /*     dum = fu; */
                   2351: /*     fu = *fc; */
                   2352: /*     *fc =dum; */
                   2353: /*       } */
1.224     brouard  2354: #ifdef DEBUGMNBRAK
                   2355:                 double A, fparabu; 
                   2356:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2357:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2358:      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);
                   2359:      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  2360: #endif
1.191     brouard  2361:       dum=u; /* Shifting c and u */
                   2362:       u = *cx;
                   2363:       *cx = dum;
                   2364:       dum = fu;
                   2365:       fu = *fc;
                   2366:       *fc =dum;
1.183     brouard  2367: #endif
1.162     brouard  2368:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2369: #ifdef DEBUG
1.224     brouard  2370:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2371:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2372: #endif
1.126     brouard  2373:       fu=(*func)(u); 
                   2374:       if (fu < *fc) { 
1.183     brouard  2375: #ifdef DEBUG
1.224     brouard  2376:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2377:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2378: #endif
                   2379:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2380:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2381: #ifdef DEBUG
                   2382:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2383: #endif
                   2384:       } 
1.162     brouard  2385:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2386: #ifdef DEBUG
1.224     brouard  2387:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2388:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2389: #endif
1.126     brouard  2390:       u=ulim; 
                   2391:       fu=(*func)(u); 
1.183     brouard  2392:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2393: #ifdef DEBUG
1.224     brouard  2394:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2395:       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  2396: #endif
1.126     brouard  2397:       u=(*cx)+GOLD*(*cx-*bx); 
                   2398:       fu=(*func)(u); 
1.224     brouard  2399: #ifdef DEBUG
                   2400:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2401:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2402: #endif
1.183     brouard  2403:     } /* end tests */
1.126     brouard  2404:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2405:     SHFT(*fa,*fb,*fc,fu) 
                   2406: #ifdef DEBUG
1.224     brouard  2407:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2408:       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  2409: #endif
                   2410:   } /* 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  2411: } 
                   2412: 
                   2413: /*************** linmin ************************/
1.162     brouard  2414: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2415: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2416: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2417: the value of func at the returned location p . This is actually all accomplished by calling the
                   2418: routines mnbrak and brent .*/
1.126     brouard  2419: int ncom; 
                   2420: double *pcom,*xicom;
                   2421: double (*nrfunc)(double []); 
                   2422:  
1.224     brouard  2423: #ifdef LINMINORIGINAL
1.126     brouard  2424: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2425: #else
                   2426: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2427: #endif
1.126     brouard  2428: { 
                   2429:   double brent(double ax, double bx, double cx, 
                   2430:               double (*f)(double), double tol, double *xmin); 
                   2431:   double f1dim(double x); 
                   2432:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2433:              double *fc, double (*func)(double)); 
                   2434:   int j; 
                   2435:   double xx,xmin,bx,ax; 
                   2436:   double fx,fb,fa;
1.187     brouard  2437: 
1.203     brouard  2438: #ifdef LINMINORIGINAL
                   2439: #else
                   2440:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2441: #endif
                   2442:   
1.126     brouard  2443:   ncom=n; 
                   2444:   pcom=vector(1,n); 
                   2445:   xicom=vector(1,n); 
                   2446:   nrfunc=func; 
                   2447:   for (j=1;j<=n;j++) { 
                   2448:     pcom[j]=p[j]; 
1.202     brouard  2449:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2450:   } 
1.187     brouard  2451: 
1.203     brouard  2452: #ifdef LINMINORIGINAL
                   2453:   xx=1.;
                   2454: #else
                   2455:   axs=0.0;
                   2456:   xxs=1.;
                   2457:   do{
                   2458:     xx= xxs;
                   2459: #endif
1.187     brouard  2460:     ax=0.;
                   2461:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2462:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2463:     /* 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))   */
                   2464:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2465:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2466:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2467:     /* 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  2468: #ifdef LINMINORIGINAL
                   2469: #else
                   2470:     if (fx != fx){
1.224     brouard  2471:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2472:                        printf("|");
                   2473:                        fprintf(ficlog,"|");
1.203     brouard  2474: #ifdef DEBUGLINMIN
1.224     brouard  2475:                        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  2476: #endif
                   2477:     }
1.224     brouard  2478:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2479: #endif
                   2480:   
1.191     brouard  2481: #ifdef DEBUGLINMIN
                   2482:   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  2483:   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  2484: #endif
1.224     brouard  2485: #ifdef LINMINORIGINAL
                   2486: #else
1.317     brouard  2487:   if(fb == fx){ /* Flat function in the direction */
                   2488:     xmin=xx;
1.224     brouard  2489:     *flat=1;
1.317     brouard  2490:   }else{
1.224     brouard  2491:     *flat=0;
                   2492: #endif
                   2493:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2494:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2495:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2496:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2497:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2498:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2499: #ifdef DEBUG
1.224     brouard  2500:   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);
                   2501:   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);
                   2502: #endif
                   2503: #ifdef LINMINORIGINAL
                   2504: #else
                   2505:                        }
1.126     brouard  2506: #endif
1.191     brouard  2507: #ifdef DEBUGLINMIN
                   2508:   printf("linmin end ");
1.202     brouard  2509:   fprintf(ficlog,"linmin end ");
1.191     brouard  2510: #endif
1.126     brouard  2511:   for (j=1;j<=n;j++) { 
1.203     brouard  2512: #ifdef LINMINORIGINAL
                   2513:     xi[j] *= xmin; 
                   2514: #else
                   2515: #ifdef DEBUGLINMIN
                   2516:     if(xxs <1.0)
                   2517:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2518: #endif
                   2519:     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) */
                   2520: #ifdef DEBUGLINMIN
                   2521:     if(xxs <1.0)
                   2522:       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 );
                   2523: #endif
                   2524: #endif
1.187     brouard  2525:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2526:   } 
1.191     brouard  2527: #ifdef DEBUGLINMIN
1.203     brouard  2528:   printf("\n");
1.191     brouard  2529:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2530:   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  2531:   for (j=1;j<=n;j++) { 
1.202     brouard  2532:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2533:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2534:     if(j % ncovmodel == 0){
1.191     brouard  2535:       printf("\n");
1.202     brouard  2536:       fprintf(ficlog,"\n");
                   2537:     }
1.191     brouard  2538:   }
1.203     brouard  2539: #else
1.191     brouard  2540: #endif
1.126     brouard  2541:   free_vector(xicom,1,n); 
                   2542:   free_vector(pcom,1,n); 
                   2543: } 
                   2544: 
                   2545: 
                   2546: /*************** powell ************************/
1.162     brouard  2547: /*
1.317     brouard  2548: Minimization of a function func of n variables. Input consists in an initial starting point
                   2549: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2550: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2551: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2552: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2553: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2554:  */
1.224     brouard  2555: #ifdef LINMINORIGINAL
                   2556: #else
                   2557:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2558:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2559: #endif
1.126     brouard  2560: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2561:            double (*func)(double [])) 
                   2562: { 
1.224     brouard  2563: #ifdef LINMINORIGINAL
                   2564:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2565:              double (*func)(double [])); 
1.224     brouard  2566: #else 
1.241     brouard  2567:  void linmin(double p[], double xi[], int n, double *fret,
                   2568:             double (*func)(double []),int *flat); 
1.224     brouard  2569: #endif
1.239     brouard  2570:  int i,ibig,j,jk,k; 
1.126     brouard  2571:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2572:   double directest;
1.126     brouard  2573:   double fp,fptt;
                   2574:   double *xits;
                   2575:   int niterf, itmp;
                   2576: 
                   2577:   pt=vector(1,n); 
                   2578:   ptt=vector(1,n); 
                   2579:   xit=vector(1,n); 
                   2580:   xits=vector(1,n); 
                   2581:   *fret=(*func)(p); 
                   2582:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2583:   rcurr_time = time(NULL);
                   2584:   fp=(*fret); /* Initialisation */
1.126     brouard  2585:   for (*iter=1;;++(*iter)) { 
                   2586:     ibig=0; 
                   2587:     del=0.0; 
1.157     brouard  2588:     rlast_time=rcurr_time;
                   2589:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2590:     rcurr_time = time(NULL);  
                   2591:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2592:     /* 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); */
                   2593:     /* 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); */
                   2594:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2595:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2596: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2597:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2598:     for (i=1;i<=n;i++) {
1.126     brouard  2599:       fprintf(ficrespow," %.12lf", p[i]);
                   2600:     }
1.239     brouard  2601:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2602:     printf("\n#model=  1      +     age ");
                   2603:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2604:     if(nagesqr==1){
1.241     brouard  2605:        printf("  + age*age  ");
                   2606:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2607:     }
                   2608:     for(j=1;j <=ncovmodel-2;j++){
                   2609:       if(Typevar[j]==0) {
                   2610:        printf("  +      V%d  ",Tvar[j]);
                   2611:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2612:       }else if(Typevar[j]==1) {
                   2613:        printf("  +    V%d*age ",Tvar[j]);
                   2614:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2615:       }else if(Typevar[j]==2) {
                   2616:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2617:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2618:       }
                   2619:     }
1.126     brouard  2620:     printf("\n");
1.239     brouard  2621: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2622: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2623:     fprintf(ficlog,"\n");
1.239     brouard  2624:     for(i=1,jk=1; i <=nlstate; i++){
                   2625:       for(k=1; k <=(nlstate+ndeath); k++){
                   2626:        if (k != i) {
                   2627:          printf("%d%d ",i,k);
                   2628:          fprintf(ficlog,"%d%d ",i,k);
                   2629:          for(j=1; j <=ncovmodel; j++){
                   2630:            printf("%12.7f ",p[jk]);
                   2631:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2632:            jk++; 
                   2633:          }
                   2634:          printf("\n");
                   2635:          fprintf(ficlog,"\n");
                   2636:        }
                   2637:       }
                   2638:     }
1.241     brouard  2639:     if(*iter <=3 && *iter >1){
1.157     brouard  2640:       tml = *localtime(&rcurr_time);
                   2641:       strcpy(strcurr,asctime(&tml));
                   2642:       rforecast_time=rcurr_time; 
1.126     brouard  2643:       itmp = strlen(strcurr);
                   2644:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2645:        strcurr[itmp-1]='\0';
1.162     brouard  2646:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2647:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2648:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2649:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2650:        forecast_time = *localtime(&rforecast_time);
                   2651:        strcpy(strfor,asctime(&forecast_time));
                   2652:        itmp = strlen(strfor);
                   2653:        if(strfor[itmp-1]=='\n')
                   2654:          strfor[itmp-1]='\0';
                   2655:        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);
                   2656:        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  2657:       }
                   2658:     }
1.187     brouard  2659:     for (i=1;i<=n;i++) { /* For each direction i */
                   2660:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2661:       fptt=(*fret); 
                   2662: #ifdef DEBUG
1.203     brouard  2663:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2664:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2665: #endif
1.203     brouard  2666:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2667:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2668: #ifdef LINMINORIGINAL
1.188     brouard  2669:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2670: #else
                   2671:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2672:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2673: #endif
                   2674:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2675:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2676:                                /* because that direction will be replaced unless the gain del is small */
                   2677:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2678:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2679:                                /* with the new direction. */
                   2680:                                del=fabs(fptt-(*fret)); 
                   2681:                                ibig=i; 
1.126     brouard  2682:       } 
                   2683: #ifdef DEBUG
                   2684:       printf("%d %.12e",i,(*fret));
                   2685:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2686:       for (j=1;j<=n;j++) {
1.224     brouard  2687:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2688:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2689:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2690:       }
                   2691:       for(j=1;j<=n;j++) {
1.225     brouard  2692:                                printf(" p(%d)=%.12e",j,p[j]);
                   2693:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2694:       }
                   2695:       printf("\n");
                   2696:       fprintf(ficlog,"\n");
                   2697: #endif
1.187     brouard  2698:     } /* end loop on each direction i */
                   2699:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2700:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2701:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2702:     for(j=1;j<=n;j++) {
                   2703:       if(flatdir[j] >0){
                   2704:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2705:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2706:       }
1.319     brouard  2707:       /* printf("\n"); */
                   2708:       /* fprintf(ficlog,"\n"); */
                   2709:     }
1.243     brouard  2710:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2711:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2712:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2713:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2714:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2715:       /* decreased of more than 3.84  */
                   2716:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2717:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2718:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2719:                        
1.188     brouard  2720:       /* Starting the program with initial values given by a former maximization will simply change */
                   2721:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2722:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2723:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2724: #ifdef DEBUG
                   2725:       int k[2],l;
                   2726:       k[0]=1;
                   2727:       k[1]=-1;
                   2728:       printf("Max: %.12e",(*func)(p));
                   2729:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2730:       for (j=1;j<=n;j++) {
                   2731:        printf(" %.12e",p[j]);
                   2732:        fprintf(ficlog," %.12e",p[j]);
                   2733:       }
                   2734:       printf("\n");
                   2735:       fprintf(ficlog,"\n");
                   2736:       for(l=0;l<=1;l++) {
                   2737:        for (j=1;j<=n;j++) {
                   2738:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2739:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2740:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2741:        }
                   2742:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2743:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2744:       }
                   2745: #endif
                   2746: 
                   2747:       free_vector(xit,1,n); 
                   2748:       free_vector(xits,1,n); 
                   2749:       free_vector(ptt,1,n); 
                   2750:       free_vector(pt,1,n); 
                   2751:       return; 
1.192     brouard  2752:     } /* enough precision */ 
1.240     brouard  2753:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2754:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2755:       ptt[j]=2.0*p[j]-pt[j]; 
                   2756:       xit[j]=p[j]-pt[j]; 
                   2757:       pt[j]=p[j]; 
                   2758:     } 
1.181     brouard  2759:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2760: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2761:                if (*iter <=4) {
1.225     brouard  2762: #else
                   2763: #endif
1.224     brouard  2764: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2765: #else
1.161     brouard  2766:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2767: #endif
1.162     brouard  2768:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2769:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2770:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2771:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2772:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2773:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2774:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2775:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2776:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2777:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2778:       /* mu² and del² are equal when f3=f1 */
                   2779:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2780:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2781:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2782:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2783: #ifdef NRCORIGINAL
                   2784:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2785: #else
                   2786:       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  2787:       t= t- del*SQR(fp-fptt);
1.183     brouard  2788: #endif
1.202     brouard  2789:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2790: #ifdef DEBUG
1.181     brouard  2791:       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);
                   2792:       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  2793:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2794:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2795:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2796:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2797:       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);
                   2798:       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);
                   2799: #endif
1.183     brouard  2800: #ifdef POWELLORIGINAL
                   2801:       if (t < 0.0) { /* Then we use it for new direction */
                   2802: #else
1.182     brouard  2803:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2804:                                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  2805:         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  2806:         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  2807:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2808:       } 
1.181     brouard  2809:       if (directest < 0.0) { /* Then we use it for new direction */
                   2810: #endif
1.191     brouard  2811: #ifdef DEBUGLINMIN
1.234     brouard  2812:        printf("Before linmin in direction P%d-P0\n",n);
                   2813:        for (j=1;j<=n;j++) {
                   2814:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2815:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2816:          if(j % ncovmodel == 0){
                   2817:            printf("\n");
                   2818:            fprintf(ficlog,"\n");
                   2819:          }
                   2820:        }
1.224     brouard  2821: #endif
                   2822: #ifdef LINMINORIGINAL
1.234     brouard  2823:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2824: #else
1.234     brouard  2825:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2826:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2827: #endif
1.234     brouard  2828:        
1.191     brouard  2829: #ifdef DEBUGLINMIN
1.234     brouard  2830:        for (j=1;j<=n;j++) { 
                   2831:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2832:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2833:          if(j % ncovmodel == 0){
                   2834:            printf("\n");
                   2835:            fprintf(ficlog,"\n");
                   2836:          }
                   2837:        }
1.224     brouard  2838: #endif
1.234     brouard  2839:        for (j=1;j<=n;j++) { 
                   2840:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2841:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2842:        }
1.224     brouard  2843: #ifdef LINMINORIGINAL
                   2844: #else
1.234     brouard  2845:        for (j=1, flatd=0;j<=n;j++) {
                   2846:          if(flatdir[j]>0)
                   2847:            flatd++;
                   2848:        }
                   2849:        if(flatd >0){
1.255     brouard  2850:          printf("%d flat directions: ",flatd);
                   2851:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2852:          for (j=1;j<=n;j++) { 
                   2853:            if(flatdir[j]>0){
                   2854:              printf("%d ",j);
                   2855:              fprintf(ficlog,"%d ",j);
                   2856:            }
                   2857:          }
                   2858:          printf("\n");
                   2859:          fprintf(ficlog,"\n");
1.319     brouard  2860: #ifdef FLATSUP
                   2861:           free_vector(xit,1,n); 
                   2862:           free_vector(xits,1,n); 
                   2863:           free_vector(ptt,1,n); 
                   2864:           free_vector(pt,1,n); 
                   2865:           return;
                   2866: #endif
1.234     brouard  2867:        }
1.191     brouard  2868: #endif
1.234     brouard  2869:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2870:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2871:        
1.126     brouard  2872: #ifdef DEBUG
1.234     brouard  2873:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2874:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2875:        for(j=1;j<=n;j++){
                   2876:          printf(" %lf",xit[j]);
                   2877:          fprintf(ficlog," %lf",xit[j]);
                   2878:        }
                   2879:        printf("\n");
                   2880:        fprintf(ficlog,"\n");
1.126     brouard  2881: #endif
1.192     brouard  2882:       } /* end of t or directest negative */
1.224     brouard  2883: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2884: #else
1.234     brouard  2885:       } /* end if (fptt < fp)  */
1.192     brouard  2886: #endif
1.225     brouard  2887: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2888:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2889: #else
1.224     brouard  2890: #endif
1.234     brouard  2891:                } /* loop iteration */ 
1.126     brouard  2892: } 
1.234     brouard  2893:   
1.126     brouard  2894: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2895:   
1.235     brouard  2896:   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  2897:   {
1.338     brouard  2898:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2899:      *   (and selected quantitative values in nres)
                   2900:      *  by left multiplying the unit
                   2901:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2902:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2903:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2904:      * or prevalence in state 1, prevalence in state 2, 0
                   2905:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2906:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2907:      * Output is prlim.
                   2908:      * Initial matrix pimij 
                   2909:      */
1.206     brouard  2910:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2911:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2912:   /*  0,                   0                  , 1} */
                   2913:   /*
                   2914:    * and after some iteration: */
                   2915:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2916:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2917:   /*  0,                   0                  , 1} */
                   2918:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2919:   /* {0.51571254859325999, 0.4842874514067399, */
                   2920:   /*  0.51326036147820708, 0.48673963852179264} */
                   2921:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2922:     
1.332     brouard  2923:     int i, ii,j,k, k1;
1.209     brouard  2924:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2925:   /* double **matprod2(); */ /* test */
1.218     brouard  2926:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2927:   double **newm;
1.209     brouard  2928:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2929:   int ncvloop=0;
1.288     brouard  2930:   int first=0;
1.169     brouard  2931:   
1.209     brouard  2932:   min=vector(1,nlstate);
                   2933:   max=vector(1,nlstate);
                   2934:   meandiff=vector(1,nlstate);
                   2935: 
1.218     brouard  2936:        /* Starting with matrix unity */
1.126     brouard  2937:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2938:     for (j=1;j<=nlstate+ndeath;j++){
                   2939:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2940:     }
1.169     brouard  2941:   
                   2942:   cov[1]=1.;
                   2943:   
                   2944:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2945:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2946:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2947:     ncvloop++;
1.126     brouard  2948:     newm=savm;
                   2949:     /* Covariates have to be included here again */
1.138     brouard  2950:     cov[2]=agefin;
1.319     brouard  2951:      if(nagesqr==1){
                   2952:       cov[3]= agefin*agefin;
                   2953:      }
1.332     brouard  2954:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2955:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2956:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2957:        if(Typevar[k1]==1){ /* A product with age */
                   2958:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2959:        }else{
                   2960:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2961:        }
                   2962:      }/* End of loop on model equation */
                   2963:      
                   2964: /* Start of old code (replaced by a loop on position in the model equation */
                   2965:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2966:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2967:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2968:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2969:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2970:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2971:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2972:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2973:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2974:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2975:     /*    *nsd=3                              (1)  (2)           (3) */
                   2976:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2977:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2978:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2979:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2980:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2981:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2982:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2983:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2984:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2985:     /*    *TvarsDpType */
                   2986:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2987:     /*    * nsd=1              (1)           (2) */
                   2988:     /*    *TvarsD[nsd]          3             2 */
                   2989:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2990:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2991:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2992:     /*    *\/ */
                   2993:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2994:     /*   /\* 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)); *\/ */
                   2995:     /* } */
                   2996:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2997:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2998:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2999:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3000:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3001:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3002:     /*   /\* 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]); *\/ */
                   3003:     /* } */
                   3004:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3005:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3006:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3007:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3008:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3009:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3010:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3011:     /*   } */
                   3012:     /*   /\* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   3013:     /* } */
                   3014:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3015:     /*   /\* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); *\/ */
                   3016:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3017:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3018:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3019:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3020:     /*         }else{ */
                   3021:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3022:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3023:     /*         } */
                   3024:     /*   }else{ */
                   3025:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3026:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3027:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3028:     /*         }else{ */
                   3029:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3030:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3031:     /*         } */
                   3032:     /*   } */
                   3033:     /* } /\* End product without age *\/ */
                   3034: /* ENd of old code */
1.138     brouard  3035:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3036:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3037:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3038:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3039:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3040:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3041:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3042:     
1.126     brouard  3043:     savm=oldm;
                   3044:     oldm=newm;
1.209     brouard  3045: 
                   3046:     for(j=1; j<=nlstate; j++){
                   3047:       max[j]=0.;
                   3048:       min[j]=1.;
                   3049:     }
                   3050:     for(i=1;i<=nlstate;i++){
                   3051:       sumnew=0;
                   3052:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3053:       for(j=1; j<=nlstate; j++){ 
                   3054:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3055:        max[j]=FMAX(max[j],prlim[i][j]);
                   3056:        min[j]=FMIN(min[j],prlim[i][j]);
                   3057:       }
                   3058:     }
                   3059: 
1.126     brouard  3060:     maxmax=0.;
1.209     brouard  3061:     for(j=1; j<=nlstate; j++){
                   3062:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3063:       maxmax=FMAX(maxmax,meandiff[j]);
                   3064:       /* 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  3065:     } /* j loop */
1.203     brouard  3066:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3067:     /* 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  3068:     if(maxmax < ftolpl){
1.209     brouard  3069:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3070:       free_vector(min,1,nlstate);
                   3071:       free_vector(max,1,nlstate);
                   3072:       free_vector(meandiff,1,nlstate);
1.126     brouard  3073:       return prlim;
                   3074:     }
1.288     brouard  3075:   } /* agefin loop */
1.208     brouard  3076:     /* After some age loop it doesn't converge */
1.288     brouard  3077:   if(!first){
                   3078:     first=1;
                   3079:     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  3080:     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);
                   3081:   }else if (first >=1 && first <10){
                   3082:     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);
                   3083:     first++;
                   3084:   }else if (first ==10){
                   3085:     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);
                   3086:     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");
                   3087:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3088:     first++;
1.288     brouard  3089:   }
                   3090: 
1.209     brouard  3091:   /* 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); */
                   3092:   free_vector(min,1,nlstate);
                   3093:   free_vector(max,1,nlstate);
                   3094:   free_vector(meandiff,1,nlstate);
1.208     brouard  3095:   
1.169     brouard  3096:   return prlim; /* should not reach here */
1.126     brouard  3097: }
                   3098: 
1.217     brouard  3099: 
                   3100:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3101: 
1.218     brouard  3102:  /* 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) */
                   3103:  /* 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  3104:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3105: {
1.264     brouard  3106:   /* 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  3107:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3108:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3109:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3110:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3111:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3112:   /* Initial matrix pimij */
                   3113:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3114:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3115:   /*  0,                   0                  , 1} */
                   3116:   /*
                   3117:    * and after some iteration: */
                   3118:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3119:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3120:   /*  0,                   0                  , 1} */
                   3121:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3122:   /* {0.51571254859325999, 0.4842874514067399, */
                   3123:   /*  0.51326036147820708, 0.48673963852179264} */
                   3124:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3125: 
1.332     brouard  3126:   int i, ii,j,k, k1;
1.247     brouard  3127:   int first=0;
1.217     brouard  3128:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3129:   /* double **matprod2(); */ /* test */
                   3130:   double **out, cov[NCOVMAX+1], **bmij();
                   3131:   double **newm;
1.218     brouard  3132:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3133:   double        **oldm, **savm;  /* for use */
                   3134: 
1.217     brouard  3135:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3136:   int ncvloop=0;
                   3137:   
                   3138:   min=vector(1,nlstate);
                   3139:   max=vector(1,nlstate);
                   3140:   meandiff=vector(1,nlstate);
                   3141: 
1.266     brouard  3142:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3143:   oldm=oldms; savm=savms;
                   3144:   
                   3145:   /* Starting with matrix unity */
                   3146:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3147:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3148:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3149:     }
                   3150:   
                   3151:   cov[1]=1.;
                   3152:   
                   3153:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3154:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3155:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3156:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3157:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3158:     ncvloop++;
1.218     brouard  3159:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3160:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3161:     /* Covariates have to be included here again */
                   3162:     cov[2]=agefin;
1.319     brouard  3163:     if(nagesqr==1){
1.217     brouard  3164:       cov[3]= agefin*agefin;;
1.319     brouard  3165:     }
1.332     brouard  3166:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3167:       if(Typevar[k1]==1){ /* A product with age */
                   3168:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3169:       }else{
1.332     brouard  3170:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3171:       }
1.332     brouard  3172:     }/* End of loop on model equation */
                   3173: 
                   3174: /* Old code */ 
                   3175: 
                   3176:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3177:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3178:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3179:     /*   /\* 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)); *\/ */
                   3180:     /* } */
                   3181:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3182:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3183:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3184:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3185:     /* /\* } *\/ */
                   3186:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3187:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3188:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3189:     /*   /\* 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]); *\/ */
                   3190:     /* } */
                   3191:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3192:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3193:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3194:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3195:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3196:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3197:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3198:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3199:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3200:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3201:     /*   } */
                   3202:     /*   /\* 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]); *\/ */
                   3203:     /* } */
                   3204:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3205:     /*   /\* 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]); *\/ */
                   3206:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3207:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3208:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3209:     /*         }else{ */
                   3210:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3211:     /*         } */
                   3212:     /*   }else{ */
                   3213:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3214:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3215:     /*         }else{ */
                   3216:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3217:     /*         } */
                   3218:     /*   } */
                   3219:     /* } */
1.217     brouard  3220:     
                   3221:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3222:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3223:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3224:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3225:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3226:                /* ij should be linked to the correct index of cov */
                   3227:                /* age and covariate values ij are in 'cov', but we need to pass
                   3228:                 * ij for the observed prevalence at age and status and covariate
                   3229:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3230:                 */
                   3231:     /* 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 *\/ */
                   3232:     /* 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 *\/ */
                   3233:     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  3234:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3235:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3236:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3237:     /*         printf("%d newm= ",i); */
                   3238:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3239:     /*           printf("%f ",newm[i][j]); */
                   3240:     /*         } */
                   3241:     /*         printf("oldm * "); */
                   3242:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3243:     /*           printf("%f ",oldm[i][j]); */
                   3244:     /*         } */
1.268     brouard  3245:     /*         printf(" bmmij "); */
1.266     brouard  3246:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3247:     /*           printf("%f ",pmmij[i][j]); */
                   3248:     /*         } */
                   3249:     /*         printf("\n"); */
                   3250:     /*   } */
                   3251:     /* } */
1.217     brouard  3252:     savm=oldm;
                   3253:     oldm=newm;
1.266     brouard  3254: 
1.217     brouard  3255:     for(j=1; j<=nlstate; j++){
                   3256:       max[j]=0.;
                   3257:       min[j]=1.;
                   3258:     }
                   3259:     for(j=1; j<=nlstate; j++){ 
                   3260:       for(i=1;i<=nlstate;i++){
1.234     brouard  3261:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3262:        bprlim[i][j]= newm[i][j];
                   3263:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3264:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3265:       }
                   3266:     }
1.218     brouard  3267:                
1.217     brouard  3268:     maxmax=0.;
                   3269:     for(i=1; i<=nlstate; i++){
1.318     brouard  3270:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3271:       maxmax=FMAX(maxmax,meandiff[i]);
                   3272:       /* 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  3273:     } /* i loop */
1.217     brouard  3274:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3275:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3276:     if(maxmax < ftolpl){
1.220     brouard  3277:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3278:       free_vector(min,1,nlstate);
                   3279:       free_vector(max,1,nlstate);
                   3280:       free_vector(meandiff,1,nlstate);
                   3281:       return bprlim;
                   3282:     }
1.288     brouard  3283:   } /* agefin loop */
1.217     brouard  3284:     /* After some age loop it doesn't converge */
1.288     brouard  3285:   if(!first){
1.247     brouard  3286:     first=1;
                   3287:     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\
                   3288: 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);
                   3289:   }
                   3290:   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  3291: 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);
                   3292:   /* 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); */
                   3293:   free_vector(min,1,nlstate);
                   3294:   free_vector(max,1,nlstate);
                   3295:   free_vector(meandiff,1,nlstate);
                   3296:   
                   3297:   return bprlim; /* should not reach here */
                   3298: }
                   3299: 
1.126     brouard  3300: /*************** transition probabilities ***************/ 
                   3301: 
                   3302: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3303: {
1.138     brouard  3304:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3305:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3306:      model to the ncovmodel covariates (including constant and age).
                   3307:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3308:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3309:      ncth covariate in the global vector x is given by the formula:
                   3310:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3311:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3312:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3313:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3314:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3315:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3316:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3317:   */
                   3318:   double s1, lnpijopii;
1.126     brouard  3319:   /*double t34;*/
1.164     brouard  3320:   int i,j, nc, ii, jj;
1.126     brouard  3321: 
1.223     brouard  3322:   for(i=1; i<= nlstate; i++){
                   3323:     for(j=1; j<i;j++){
                   3324:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3325:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3326:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3327:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3328:       }
                   3329:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3330:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3331:     }
                   3332:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3333:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3334:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3335:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3336:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3337:       }
                   3338:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3339:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3340:     }
                   3341:   }
1.218     brouard  3342:   
1.223     brouard  3343:   for(i=1; i<= nlstate; i++){
                   3344:     s1=0;
                   3345:     for(j=1; j<i; j++){
1.339     brouard  3346:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3347:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3348:     }
                   3349:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3350:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3351:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3352:     }
                   3353:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3354:     ps[i][i]=1./(s1+1.);
                   3355:     /* Computing other pijs */
                   3356:     for(j=1; j<i; j++)
1.325     brouard  3357:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3358:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3359:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3360:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3361:   } /* end i */
1.218     brouard  3362:   
1.223     brouard  3363:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3364:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3365:       ps[ii][jj]=0;
                   3366:       ps[ii][ii]=1;
                   3367:     }
                   3368:   }
1.294     brouard  3369: 
                   3370: 
1.223     brouard  3371:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3372:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3373:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3374:   /*   } */
                   3375:   /*   printf("\n "); */
                   3376:   /* } */
                   3377:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3378:   /*
                   3379:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3380:                goto end;*/
1.266     brouard  3381:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3382: }
                   3383: 
1.218     brouard  3384: /*************** backward transition probabilities ***************/ 
                   3385: 
                   3386:  /* 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 ) */
                   3387: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3388:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3389: {
1.302     brouard  3390:   /* 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  3391:    * 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  3392:    */
1.218     brouard  3393:   int i, ii, j,k;
1.222     brouard  3394:   
                   3395:   double **out, **pmij();
                   3396:   double sumnew=0.;
1.218     brouard  3397:   double agefin;
1.292     brouard  3398:   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  3399:   double **dnewm, **dsavm, **doldm;
                   3400:   double **bbmij;
                   3401:   
1.218     brouard  3402:   doldm=ddoldms; /* global pointers */
1.222     brouard  3403:   dnewm=ddnewms;
                   3404:   dsavm=ddsavms;
1.318     brouard  3405: 
                   3406:   /* Debug */
                   3407:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3408:   agefin=cov[2];
1.268     brouard  3409:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3410:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3411:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3412:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3413: 
                   3414:   /* P_x */
1.325     brouard  3415:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3416:   /* outputs pmmij which is a stochastic matrix in row */
                   3417: 
                   3418:   /* Diag(w_x) */
1.292     brouard  3419:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3420:   sumnew=0.;
1.269     brouard  3421:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3422:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3423:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3424:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3425:   }
                   3426:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3427:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3428:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3429:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3430:     }
                   3431:   }else{
                   3432:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3433:       for (j=1;j<=nlstate+ndeath;j++)
                   3434:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3435:     }
                   3436:     /* if(sumnew <0.9){ */
                   3437:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3438:     /* } */
                   3439:   }
                   3440:   k3=0.0;  /* We put the last diagonal to 0 */
                   3441:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3442:       doldm[ii][ii]= k3;
                   3443:   }
                   3444:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3445:   
1.292     brouard  3446:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3447:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3448: 
1.292     brouard  3449:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3450:   /* 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  3451:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3452:     sumnew=0.;
1.222     brouard  3453:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3454:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3455:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3456:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3457:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3458:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3459:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3460:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3461:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3462:        /* }else */
1.268     brouard  3463:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3464:     } /*End ii */
                   3465:   } /* 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 */
                   3466: 
1.292     brouard  3467:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3468:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3469:   /* end bmij */
1.266     brouard  3470:   return ps; /*pointer is unchanged */
1.218     brouard  3471: }
1.217     brouard  3472: /*************** transition probabilities ***************/ 
                   3473: 
1.218     brouard  3474: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3475: {
                   3476:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3477:      computes the probability to be observed in state j being in state i by appying the
                   3478:      model to the ncovmodel covariates (including constant and age).
                   3479:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3480:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3481:      ncth covariate in the global vector x is given by the formula:
                   3482:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3483:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3484:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3485:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3486:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3487:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3488:   */
                   3489:   double s1, lnpijopii;
                   3490:   /*double t34;*/
                   3491:   int i,j, nc, ii, jj;
                   3492: 
1.234     brouard  3493:   for(i=1; i<= nlstate; i++){
                   3494:     for(j=1; j<i;j++){
                   3495:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3496:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3497:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3498:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3499:       }
                   3500:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3501:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3502:     }
                   3503:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3504:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3505:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3506:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3507:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3508:       }
                   3509:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3510:     }
                   3511:   }
                   3512:   
                   3513:   for(i=1; i<= nlstate; i++){
                   3514:     s1=0;
                   3515:     for(j=1; j<i; j++){
                   3516:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3517:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3518:     }
                   3519:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3520:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3521:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3522:     }
                   3523:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3524:     ps[i][i]=1./(s1+1.);
                   3525:     /* Computing other pijs */
                   3526:     for(j=1; j<i; j++)
                   3527:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3528:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3529:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3530:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3531:   } /* end i */
                   3532:   
                   3533:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3534:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3535:       ps[ii][jj]=0;
                   3536:       ps[ii][ii]=1;
                   3537:     }
                   3538:   }
1.296     brouard  3539:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3540:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3541:     s1=0.;
                   3542:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3543:       s1+=ps[ii][jj];
                   3544:     }
                   3545:     for(ii=1; ii<= nlstate; ii++){
                   3546:       ps[ii][jj]=ps[ii][jj]/s1;
                   3547:     }
                   3548:   }
                   3549:   /* Transposition */
                   3550:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3551:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3552:       s1=ps[ii][jj];
                   3553:       ps[ii][jj]=ps[jj][ii];
                   3554:       ps[jj][ii]=s1;
                   3555:     }
                   3556:   }
                   3557:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3558:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3559:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3560:   /*   } */
                   3561:   /*   printf("\n "); */
                   3562:   /* } */
                   3563:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3564:   /*
                   3565:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3566:     goto end;*/
                   3567:   return ps;
1.217     brouard  3568: }
                   3569: 
                   3570: 
1.126     brouard  3571: /**************** Product of 2 matrices ******************/
                   3572: 
1.145     brouard  3573: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3574: {
                   3575:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3576:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3577:   /* in, b, out are matrice of pointers which should have been initialized 
                   3578:      before: only the contents of out is modified. The function returns
                   3579:      a pointer to pointers identical to out */
1.145     brouard  3580:   int i, j, k;
1.126     brouard  3581:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3582:     for(k=ncolol; k<=ncoloh; k++){
                   3583:       out[i][k]=0.;
                   3584:       for(j=ncl; j<=nch; j++)
                   3585:        out[i][k] +=in[i][j]*b[j][k];
                   3586:     }
1.126     brouard  3587:   return out;
                   3588: }
                   3589: 
                   3590: 
                   3591: /************* Higher Matrix Product ***************/
                   3592: 
1.235     brouard  3593: 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  3594: {
1.336     brouard  3595:   /* Already optimized with precov.
                   3596:      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  3597:      'nhstepm*hstepm*stepm' months (i.e. until
                   3598:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3599:      nhstepm*hstepm matrices. 
                   3600:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3601:      (typically every 2 years instead of every month which is too big 
                   3602:      for the memory).
                   3603:      Model is determined by parameters x and covariates have to be 
                   3604:      included manually here. 
                   3605: 
                   3606:      */
                   3607: 
1.330     brouard  3608:   int i, j, d, h, k, k1;
1.131     brouard  3609:   double **out, cov[NCOVMAX+1];
1.126     brouard  3610:   double **newm;
1.187     brouard  3611:   double agexact;
1.214     brouard  3612:   double agebegin, ageend;
1.126     brouard  3613: 
                   3614:   /* Hstepm could be zero and should return the unit matrix */
                   3615:   for (i=1;i<=nlstate+ndeath;i++)
                   3616:     for (j=1;j<=nlstate+ndeath;j++){
                   3617:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3618:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3619:     }
                   3620:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3621:   for(h=1; h <=nhstepm; h++){
                   3622:     for(d=1; d <=hstepm; d++){
                   3623:       newm=savm;
                   3624:       /* Covariates have to be included here again */
                   3625:       cov[1]=1.;
1.214     brouard  3626:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3627:       cov[2]=agexact;
1.319     brouard  3628:       if(nagesqr==1){
1.227     brouard  3629:        cov[3]= agexact*agexact;
1.319     brouard  3630:       }
1.330     brouard  3631:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3632:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3633:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3634:        if(Typevar[k1]==1){ /* A product with age */
                   3635:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3636:        }else{
                   3637:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3638:        }
                   3639:       }/* End of loop on model equation */
                   3640:        /* Old code */ 
                   3641: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3642: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3643: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3644: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3645: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3646: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3647: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3648: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3649: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3650: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3651: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3652: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3653: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3654: /*       /\* 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]])); *\/ */
                   3655: /*       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); */
                   3656: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3657: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3658: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3659: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3660: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3661: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3662: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3663: /*       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]]); */
                   3664: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3665: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3666: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3667: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3668: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3669: /*       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]); */
                   3670: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3671: 
                   3672: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3673: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3674: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3675: /*       /\* *\/ */
1.330     brouard  3676: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3677: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3678: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3679: /* /\*cptcovage=2                   1               2      *\/ */
                   3680: /* /\*Tage[k]=                      5               8      *\/  */
                   3681: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3682: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3683: /*       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]]); */
                   3684: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3685: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3686: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3687: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3688: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3689: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3690: /*       /\*   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); *\/ */
                   3691: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3692: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3693: /*       /\* } *\/ */
                   3694: /*       /\* 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]); *\/ */
                   3695: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3696: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3697: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3698: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3699: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3700: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3701: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3702: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3703: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3704:          
1.332     brouard  3705: /*       /\* 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])]); *\/ */
                   3706: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3707: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3708: /*       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]]); */
                   3709: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3710: 
                   3711: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3712: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3713: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3714: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3715: /*           /\* 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]])]; *\/ */
                   3716: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3717: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3718: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3719: /*       /\*   } *\/ */
                   3720: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3721: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3722: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3723: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3724: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3725: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3726: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3727: /*       /\*   } *\/ */
                   3728: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3729: /*     }/\*end of products *\/ */
                   3730:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3731:       /* for (k=1; k<=cptcovn;k++)  */
                   3732:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3733:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3734:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3735:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3736:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3737:       
                   3738:       
1.126     brouard  3739:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3740:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3741:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3742:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3743:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3744:       /* if((int)age == 70){ */
                   3745:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3746:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3747:       /*         printf("%d pmmij ",i); */
                   3748:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3749:       /*           printf("%f ",pmmij[i][j]); */
                   3750:       /*         } */
                   3751:       /*         printf(" oldm "); */
                   3752:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3753:       /*           printf("%f ",oldm[i][j]); */
                   3754:       /*         } */
                   3755:       /*         printf("\n"); */
                   3756:       /*       } */
                   3757:       /* } */
1.126     brouard  3758:       savm=oldm;
                   3759:       oldm=newm;
                   3760:     }
                   3761:     for(i=1; i<=nlstate+ndeath; i++)
                   3762:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3763:        po[i][j][h]=newm[i][j];
                   3764:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3765:       }
1.128     brouard  3766:     /*printf("h=%d ",h);*/
1.126     brouard  3767:   } /* end h */
1.267     brouard  3768:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3769:   return po;
                   3770: }
                   3771: 
1.217     brouard  3772: /************* Higher Back Matrix Product ***************/
1.218     brouard  3773: /* 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  3774: 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  3775: {
1.332     brouard  3776:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3777:      computes the transition matrix starting at age 'age' over
1.217     brouard  3778:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3779:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3780:      nhstepm*hstepm matrices.
                   3781:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3782:      (typically every 2 years instead of every month which is too big
1.217     brouard  3783:      for the memory).
1.218     brouard  3784:      Model is determined by parameters x and covariates have to be
1.266     brouard  3785:      included manually here. Then we use a call to bmij(x and cov)
                   3786:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3787:   */
1.217     brouard  3788: 
1.332     brouard  3789:   int i, j, d, h, k, k1;
1.266     brouard  3790:   double **out, cov[NCOVMAX+1], **bmij();
                   3791:   double **newm, ***newmm;
1.217     brouard  3792:   double agexact;
                   3793:   double agebegin, ageend;
1.222     brouard  3794:   double **oldm, **savm;
1.217     brouard  3795: 
1.266     brouard  3796:   newmm=po; /* To be saved */
                   3797:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3798:   /* Hstepm could be zero and should return the unit matrix */
                   3799:   for (i=1;i<=nlstate+ndeath;i++)
                   3800:     for (j=1;j<=nlstate+ndeath;j++){
                   3801:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3802:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3803:     }
                   3804:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3805:   for(h=1; h <=nhstepm; h++){
                   3806:     for(d=1; d <=hstepm; d++){
                   3807:       newm=savm;
                   3808:       /* Covariates have to be included here again */
                   3809:       cov[1]=1.;
1.271     brouard  3810:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3811:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3812:         /* Debug */
                   3813:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3814:       cov[2]=agexact;
1.332     brouard  3815:       if(nagesqr==1){
1.222     brouard  3816:        cov[3]= agexact*agexact;
1.332     brouard  3817:       }
                   3818:       /** New code */
                   3819:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3820:        if(Typevar[k1]==1){ /* A product with age */
                   3821:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3822:        }else{
1.332     brouard  3823:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3824:        }
1.332     brouard  3825:       }/* End of loop on model equation */
                   3826:       /** End of new code */
                   3827:   /** This was old code */
                   3828:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3829:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3830:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3831:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3832:       /*   /\* 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)); *\/ */
                   3833:       /* } */
                   3834:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3835:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3836:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3837:       /*       /\* 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]); *\/ */
                   3838:       /* } */
                   3839:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3840:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3841:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3842:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3843:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3844:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3845:       /*       } */
                   3846:       /*       /\* 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]); *\/ */
                   3847:       /* } */
                   3848:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3849:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3850:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3851:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3852:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3853:       /*         }else{ */
                   3854:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3855:       /*         } */
                   3856:       /*       }else{ */
                   3857:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3858:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3859:       /*         }else{ */
                   3860:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3861:       /*         } */
                   3862:       /*       } */
                   3863:       /* }                      */
                   3864:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3865:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3866: /** End of old code */
                   3867:       
1.218     brouard  3868:       /* Careful transposed matrix */
1.266     brouard  3869:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3870:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3871:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3872:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3873:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3874:       /* if((int)age == 70){ */
                   3875:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3876:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3877:       /*         printf("%d pmmij ",i); */
                   3878:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3879:       /*           printf("%f ",pmmij[i][j]); */
                   3880:       /*         } */
                   3881:       /*         printf(" oldm "); */
                   3882:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3883:       /*           printf("%f ",oldm[i][j]); */
                   3884:       /*         } */
                   3885:       /*         printf("\n"); */
                   3886:       /*       } */
                   3887:       /* } */
                   3888:       savm=oldm;
                   3889:       oldm=newm;
                   3890:     }
                   3891:     for(i=1; i<=nlstate+ndeath; i++)
                   3892:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3893:        po[i][j][h]=newm[i][j];
1.268     brouard  3894:        /* if(h==nhstepm) */
                   3895:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3896:       }
1.268     brouard  3897:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3898:   } /* end h */
1.268     brouard  3899:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3900:   return po;
                   3901: }
                   3902: 
                   3903: 
1.162     brouard  3904: #ifdef NLOPT
                   3905:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3906:   double fret;
                   3907:   double *xt;
                   3908:   int j;
                   3909:   myfunc_data *d2 = (myfunc_data *) pd;
                   3910: /* xt = (p1-1); */
                   3911:   xt=vector(1,n); 
                   3912:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3913: 
                   3914:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3915:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3916:   printf("Function = %.12lf ",fret);
                   3917:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3918:   printf("\n");
                   3919:  free_vector(xt,1,n);
                   3920:   return fret;
                   3921: }
                   3922: #endif
1.126     brouard  3923: 
                   3924: /*************** log-likelihood *************/
                   3925: double func( double *x)
                   3926: {
1.336     brouard  3927:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3928:   int ioffset=0;
1.339     brouard  3929:   int ipos=0,iposold=0,ncovv=0;
                   3930: 
1.340     brouard  3931:   double cotvarv, cotvarvold;
1.226     brouard  3932:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3933:   double **out;
                   3934:   double lli; /* Individual log likelihood */
                   3935:   int s1, s2;
1.228     brouard  3936:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.336     brouard  3937: 
1.226     brouard  3938:   double bbh, survp;
                   3939:   double agexact;
1.336     brouard  3940:   double agebegin, ageend;
1.226     brouard  3941:   /*extern weight */
                   3942:   /* We are differentiating ll according to initial status */
                   3943:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3944:   /*for(i=1;i<imx;i++) 
                   3945:     printf(" %d\n",s[4][i]);
                   3946:   */
1.162     brouard  3947: 
1.226     brouard  3948:   ++countcallfunc;
1.162     brouard  3949: 
1.226     brouard  3950:   cov[1]=1.;
1.126     brouard  3951: 
1.226     brouard  3952:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3953:   ioffset=0;
1.226     brouard  3954:   if(mle==1){
                   3955:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3956:       /* Computes the values of the ncovmodel covariates of the model
                   3957:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3958:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3959:         to be observed in j being in i according to the model.
                   3960:       */
1.243     brouard  3961:       ioffset=2+nagesqr ;
1.233     brouard  3962:    /* Fixed */
1.345     brouard  3963:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  3964:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3965:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3966:        /*  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  3967:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3968:        cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
1.319     brouard  3969:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3970:       }
1.226     brouard  3971:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3972:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3973:         has been calculated etc */
                   3974:       /* For an individual i, wav[i] gives the number of effective waves */
                   3975:       /* We compute the contribution to Likelihood of each effective transition
                   3976:         mw[mi][i] is real wave of the mi th effectve wave */
                   3977:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3978:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3979:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
1.226     brouard  3980:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3981:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3982:       */
1.336     brouard  3983:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3984:       /* Wave varying (but not age varying) */
1.339     brouard  3985:        /* 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*\/ */
                   3986:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3987:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3988:        /* } */
1.340     brouard  3989:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3990:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3991:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  3992:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  3993:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3994:          }else{ /* fixed covariate */
1.345     brouard  3995:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  3996:          }
1.339     brouard  3997:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3998:            cotvarvold=cotvarv;
                   3999:          }else{ /* A second product */
                   4000:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4001:          }
                   4002:          iposold=ipos;
1.340     brouard  4003:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4004:        }
1.339     brouard  4005:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   4006:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4007:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   4008:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   4009:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   4010:        /*   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]); */
                   4011:        /* } */
                   4012:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   4013:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4014:        /*   /\* 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]); *\/ */
                   4015:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4016:        /* } */
                   4017:        /* for products of time varying to be done */
1.234     brouard  4018:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4019:          for (j=1;j<=nlstate+ndeath;j++){
                   4020:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4021:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4022:          }
1.336     brouard  4023: 
                   4024:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4025:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
1.234     brouard  4026:        for(d=0; d<dh[mi][i]; d++){
                   4027:          newm=savm;
                   4028:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4029:          cov[2]=agexact;
                   4030:          if(nagesqr==1)
                   4031:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4032:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4033:            if(!FixedV[Tvar[Tage[kk]]])
                   4034:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4035:            else
1.341     brouard  4036:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.234     brouard  4037:          }
                   4038:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4039:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4040:          savm=oldm;
                   4041:          oldm=newm;
                   4042:        } /* end mult */
                   4043:        
                   4044:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4045:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4046:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4047:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4048:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4049:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4050:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4051:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4052:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4053:                                 * -stepm/2 to stepm/2 .
                   4054:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4055:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4056:                                 */
1.234     brouard  4057:        s1=s[mw[mi][i]][i];
                   4058:        s2=s[mw[mi+1][i]][i];
                   4059:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4060:        /* bias bh is positive if real duration
                   4061:         * is higher than the multiple of stepm and negative otherwise.
                   4062:         */
                   4063:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4064:        if( s2 > nlstate){ 
                   4065:          /* i.e. if s2 is a death state and if the date of death is known 
                   4066:             then the contribution to the likelihood is the probability to 
                   4067:             die between last step unit time and current  step unit time, 
                   4068:             which is also equal to probability to die before dh 
                   4069:             minus probability to die before dh-stepm . 
                   4070:             In version up to 0.92 likelihood was computed
                   4071:             as if date of death was unknown. Death was treated as any other
                   4072:             health state: the date of the interview describes the actual state
                   4073:             and not the date of a change in health state. The former idea was
                   4074:             to consider that at each interview the state was recorded
                   4075:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4076:             introduced the exact date of death then we should have modified
                   4077:             the contribution of an exact death to the likelihood. This new
                   4078:             contribution is smaller and very dependent of the step unit
                   4079:             stepm. It is no more the probability to die between last interview
                   4080:             and month of death but the probability to survive from last
                   4081:             interview up to one month before death multiplied by the
                   4082:             probability to die within a month. Thanks to Chris
                   4083:             Jackson for correcting this bug.  Former versions increased
                   4084:             mortality artificially. The bad side is that we add another loop
                   4085:             which slows down the processing. The difference can be up to 10%
                   4086:             lower mortality.
                   4087:          */
                   4088:          /* If, at the beginning of the maximization mostly, the
                   4089:             cumulative probability or probability to be dead is
                   4090:             constant (ie = 1) over time d, the difference is equal to
                   4091:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4092:             s1 at precedent wave, to be dead a month before current
                   4093:             wave is equal to probability, being at state s1 at
                   4094:             precedent wave, to be dead at mont of the current
                   4095:             wave. Then the observed probability (that this person died)
                   4096:             is null according to current estimated parameter. In fact,
                   4097:             it should be very low but not zero otherwise the log go to
                   4098:             infinity.
                   4099:          */
1.183     brouard  4100: /* #ifdef INFINITYORIGINAL */
                   4101: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4102: /* #else */
                   4103: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4104: /*         lli=log(mytinydouble); */
                   4105: /*       else */
                   4106: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4107: /* #endif */
1.226     brouard  4108:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4109:          
1.226     brouard  4110:        } else if  ( s2==-1 ) { /* alive */
                   4111:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4112:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4113:          /*survp += out[s1][j]; */
                   4114:          lli= log(survp);
                   4115:        }
1.336     brouard  4116:        /* else if  (s2==-4) {  */
                   4117:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4118:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4119:        /*   lli= log(survp);  */
                   4120:        /* }  */
                   4121:        /* else if  (s2==-5) {  */
                   4122:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4123:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4124:        /*   lli= log(survp);  */
                   4125:        /* }  */
1.226     brouard  4126:        else{
                   4127:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4128:          /*  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 */
                   4129:        } 
                   4130:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4131:        /*if(lli ==000.0)*/
1.340     brouard  4132:        /* printf("num[i], i=%d, 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); */
1.226     brouard  4133:        ipmx +=1;
                   4134:        sw += weight[i];
                   4135:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4136:        /* if (lli < log(mytinydouble)){ */
                   4137:        /*   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); */
                   4138:        /*   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]); */
                   4139:        /* } */
                   4140:       } /* end of wave */
                   4141:     } /* end of individual */
                   4142:   }  else if(mle==2){
                   4143:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4144:       ioffset=2+nagesqr ;
                   4145:       for (k=1; k<=ncovf;k++)
                   4146:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4147:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4148:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4149:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.319     brouard  4150:        }
1.226     brouard  4151:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4152:          for (j=1;j<=nlstate+ndeath;j++){
                   4153:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4154:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4155:          }
                   4156:        for(d=0; d<=dh[mi][i]; d++){
                   4157:          newm=savm;
                   4158:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4159:          cov[2]=agexact;
                   4160:          if(nagesqr==1)
                   4161:            cov[3]= agexact*agexact;
                   4162:          for (kk=1; kk<=cptcovage;kk++) {
                   4163:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4164:          }
                   4165:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4166:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4167:          savm=oldm;
                   4168:          oldm=newm;
                   4169:        } /* end mult */
                   4170:       
                   4171:        s1=s[mw[mi][i]][i];
                   4172:        s2=s[mw[mi+1][i]][i];
                   4173:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4174:        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 */
                   4175:        ipmx +=1;
                   4176:        sw += weight[i];
                   4177:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4178:       } /* end of wave */
                   4179:     } /* end of individual */
                   4180:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4181:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4182:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4183:       for(mi=1; mi<= wav[i]-1; mi++){
                   4184:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4185:          for (j=1;j<=nlstate+ndeath;j++){
                   4186:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4187:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4188:          }
                   4189:        for(d=0; d<dh[mi][i]; d++){
                   4190:          newm=savm;
                   4191:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4192:          cov[2]=agexact;
                   4193:          if(nagesqr==1)
                   4194:            cov[3]= agexact*agexact;
                   4195:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4196:            if(!FixedV[Tvar[Tage[kk]]])
                   4197:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4198:            else
1.341     brouard  4199:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  4200:          }
                   4201:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4202:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4203:          savm=oldm;
                   4204:          oldm=newm;
                   4205:        } /* end mult */
                   4206:       
                   4207:        s1=s[mw[mi][i]][i];
                   4208:        s2=s[mw[mi+1][i]][i];
                   4209:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4210:        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 */
                   4211:        ipmx +=1;
                   4212:        sw += weight[i];
                   4213:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4214:       } /* end of wave */
                   4215:     } /* end of individual */
                   4216:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4217:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4218:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4219:       for(mi=1; mi<= wav[i]-1; mi++){
                   4220:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4221:          for (j=1;j<=nlstate+ndeath;j++){
                   4222:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4223:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4224:          }
                   4225:        for(d=0; d<dh[mi][i]; d++){
                   4226:          newm=savm;
                   4227:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4228:          cov[2]=agexact;
                   4229:          if(nagesqr==1)
                   4230:            cov[3]= agexact*agexact;
                   4231:          for (kk=1; kk<=cptcovage;kk++) {
                   4232:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4233:          }
1.126     brouard  4234:        
1.226     brouard  4235:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4236:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4237:          savm=oldm;
                   4238:          oldm=newm;
                   4239:        } /* end mult */
                   4240:       
                   4241:        s1=s[mw[mi][i]][i];
                   4242:        s2=s[mw[mi+1][i]][i];
                   4243:        if( s2 > nlstate){ 
                   4244:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4245:        } else if  ( s2==-1 ) { /* alive */
                   4246:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4247:            survp += out[s1][j];
                   4248:          lli= log(survp);
                   4249:        }else{
                   4250:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4251:        }
                   4252:        ipmx +=1;
                   4253:        sw += weight[i];
                   4254:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4255:        /* printf("num[i]=%09ld, 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",num[i],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.226     brouard  4256:       } /* end of wave */
                   4257:     } /* end of individual */
                   4258:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4259:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4260:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4261:       for(mi=1; mi<= wav[i]-1; mi++){
                   4262:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4263:          for (j=1;j<=nlstate+ndeath;j++){
                   4264:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4265:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4266:          }
                   4267:        for(d=0; d<dh[mi][i]; d++){
                   4268:          newm=savm;
                   4269:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4270:          cov[2]=agexact;
                   4271:          if(nagesqr==1)
                   4272:            cov[3]= agexact*agexact;
                   4273:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4274:            if(!FixedV[Tvar[Tage[kk]]])
                   4275:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4276:            else
1.341     brouard  4277:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  4278:          }
1.126     brouard  4279:        
1.226     brouard  4280:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4281:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4282:          savm=oldm;
                   4283:          oldm=newm;
                   4284:        } /* end mult */
                   4285:       
                   4286:        s1=s[mw[mi][i]][i];
                   4287:        s2=s[mw[mi+1][i]][i];
                   4288:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4289:        ipmx +=1;
                   4290:        sw += weight[i];
                   4291:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4292:        /*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]);*/
                   4293:       } /* end of wave */
                   4294:     } /* end of individual */
                   4295:   } /* End of if */
                   4296:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4297:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4298:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4299:   return -l;
1.126     brouard  4300: }
                   4301: 
                   4302: /*************** log-likelihood *************/
                   4303: double funcone( double *x)
                   4304: {
1.228     brouard  4305:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4306:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4307:   int ioffset=0;
1.339     brouard  4308:   int ipos=0,iposold=0,ncovv=0;
                   4309: 
1.340     brouard  4310:   double cotvarv, cotvarvold;
1.131     brouard  4311:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4312:   double **out;
                   4313:   double lli; /* Individual log likelihood */
                   4314:   double llt;
                   4315:   int s1, s2;
1.228     brouard  4316:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4317: 
1.126     brouard  4318:   double bbh, survp;
1.187     brouard  4319:   double agexact;
1.214     brouard  4320:   double agebegin, ageend;
1.126     brouard  4321:   /*extern weight */
                   4322:   /* We are differentiating ll according to initial status */
                   4323:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4324:   /*for(i=1;i<imx;i++) 
                   4325:     printf(" %d\n",s[4][i]);
                   4326:   */
                   4327:   cov[1]=1.;
                   4328: 
                   4329:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4330:   ioffset=0;
                   4331:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4332:     /* Computes the values of the ncovmodel covariates of the model
                   4333:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4334:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4335:        to be observed in j being in i according to the model.
                   4336:     */
1.243     brouard  4337:     /* ioffset=2+nagesqr+cptcovage; */
                   4338:     ioffset=2+nagesqr;
1.232     brouard  4339:     /* Fixed */
1.224     brouard  4340:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4341:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4342:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4343:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4344:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4345:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4346:       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  4347: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4348: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4349: /*    cov[2+6]=covar[2][i]; V2  */
                   4350: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4351: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4352: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4353: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4354: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4355: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4356:     }
1.336     brouard  4357:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4358:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4359:         has been calculated etc */
                   4360:       /* For an individual i, wav[i] gives the number of effective waves */
                   4361:       /* We compute the contribution to Likelihood of each effective transition
                   4362:         mw[mi][i] is real wave of the mi th effectve wave */
                   4363:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4364:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4365:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4366:       */
                   4367:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4368:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4369:     /*   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?)*\/ */
                   4370:     /* } */
1.231     brouard  4371:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4372:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4373:     /* } */
1.225     brouard  4374:     
1.233     brouard  4375: 
                   4376:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4377:       /* Wave varying (but not age varying) *//* V1+V3+age*V1+age*V3+V1*V3 with V4 tv and V5 tvq k= 1 to 5 and extra at V(5+1)=6 for V1*V3 */
                   4378:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4379:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4380:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4381:       /* } */
                   4382:       
                   4383:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4384:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4385:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4386:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4387:       /* We need the position of the time varying or product in the model */
                   4388:       /* TvarVVind={2,5,5}, for V3 at position 2 and then the product V1*V3 is decomposed into V1 and V3 but at same position 5 */            
                   4389:       /* TvarVV gives the variable name */
1.340     brouard  4390:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4391:       *      k=         1   2     3     4         5        6        7       8        9
                   4392:       *  varying            1     2                                 3       4        5
                   4393:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4394:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4395:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4396:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4397:       */
1.345     brouard  4398:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.346     brouard  4399:        * V2 V3 V4 are fixed V6 V7 are timevarying so V8 and V5 are not in the model and product column will start at 9 Tvar[4]=6
1.345     brouard  4400:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
                   4401:        *             V1  V2     V3    V4   V5 V6     V7  V8
                   4402:        *             0   0      0      0    0  1      1   1 
                   4403:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4
                   4404:        * kmodel           1     2      3      4      5        6         7         8         9        10        11
                   4405:        * ncovf            1     2      3
                   4406:        * ncovvt=14                            1      2       3 4       5 6       7 8       9 10     11 12     13 14
                   4407:        * TvarVV[1]@14 = itv                   {6,     7,     6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4408:        * TvarVVind[1]@14=                    {4,     5,      6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4409:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
                   4410:        * Tvar[1]@20=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14}
                   4411:        * TvarFind[itv]                        0      0       0
                   4412:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4413:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4414:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4415:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4416:        *   fixed covar[itv]                  [6]     [7]    [6][2]                            
                   4417:        */
                   4418: 
1.340     brouard  4419:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
1.345     brouard  4420:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product  */
1.340     brouard  4421:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4422:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4423:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4424:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4425:        }else{ /* fixed covariate */
1.345     brouard  4426:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4427:          cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  4428:        }
1.339     brouard  4429:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4430:          cotvarvold=cotvarv;
                   4431:        }else{ /* A second product */
                   4432:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4433:        }
                   4434:        iposold=ipos;
1.340     brouard  4435:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4436:        /* For products */
                   4437:       }
                   4438:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4439:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4440:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4441:       /*       /\*           1  2   3      4      5                         *\/ */
                   4442:       /*       /\*itv           1                                           *\/ */
                   4443:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4444:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4445:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4446:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4447:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4448:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4449:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4450:       /*       /\* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][itv][i]=%f\n", i, mi, itv, TvarVDind[itv],cotvar[mw[mi][i]][itv][i]); *\/ */
                   4451:       /* } */
1.232     brouard  4452:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4453:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4454:       /*       /\* 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]); *\/ */
                   4455:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4456:       /* } */
1.126     brouard  4457:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4458:        for (j=1;j<=nlstate+ndeath;j++){
                   4459:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4460:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4461:        }
1.214     brouard  4462:       
                   4463:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4464:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4465:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4466:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4467:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4468:          and mw[mi+1][i]. dh depends on stepm.*/
                   4469:        newm=savm;
1.247     brouard  4470:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4471:        cov[2]=agexact;
                   4472:        if(nagesqr==1)
                   4473:          cov[3]= agexact*agexact;
                   4474:        for (kk=1; kk<=cptcovage;kk++) {
                   4475:          if(!FixedV[Tvar[Tage[kk]]])
                   4476:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4477:          else
1.341     brouard  4478:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.242     brouard  4479:        }
                   4480:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4481:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4482:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4483:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4484:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4485:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4486:        savm=oldm;
                   4487:        oldm=newm;
1.126     brouard  4488:       } /* end mult */
1.336     brouard  4489:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4490:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4491:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4492:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4493:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4494:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4495:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4496:         * probability in order to take into account the bias as a fraction of the way
                   4497:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4498:                                 * -stepm/2 to stepm/2 .
                   4499:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4500:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4501:                                 */
1.126     brouard  4502:       s1=s[mw[mi][i]][i];
                   4503:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4504:       /* if(s2==-1){ */
1.268     brouard  4505:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4506:       /*       /\* exit(1); *\/ */
                   4507:       /* } */
1.126     brouard  4508:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4509:       /* bias is positive if real duration
                   4510:        * is higher than the multiple of stepm and negative otherwise.
                   4511:        */
                   4512:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4513:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4514:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4515:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4516:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4517:        lli= log(survp);
1.126     brouard  4518:       }else if (mle==1){
1.242     brouard  4519:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4520:       } else if(mle==2){
1.242     brouard  4521:        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  4522:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4523:        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  4524:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4525:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4526:       } else{  /* mle=0 back to 1 */
1.242     brouard  4527:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4528:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4529:       } /* End of if */
                   4530:       ipmx +=1;
                   4531:       sw += weight[i];
                   4532:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4533:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4534:       /* printf("num[i]=%09ld, 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",num[i],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  4535:       if(globpr){
1.246     brouard  4536:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4537:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4538:                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  4539:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4540:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4541:        /* %11.6f %11.6f %11.6f ", \ */
                   4542:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4543:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4544:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4545:          llt +=ll[k]*gipmx/gsw;
                   4546:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4547:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4548:        }
1.343     brouard  4549:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4550:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4551:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4552:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4553:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4554:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4555:        }
                   4556:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4557:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4558:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4559:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4560:            /* printf(" %g",cov[ioffset+ipos]); */
                   4561:          }else{
                   4562:            fprintf(ficresilk,"*");
                   4563:            /* printf("*"); */
1.342     brouard  4564:          }
1.343     brouard  4565:          iposold=ipos;
                   4566:        }
                   4567:        for (kk=1; kk<=cptcovage;kk++) {
                   4568:          if(!FixedV[Tvar[Tage[kk]]]){
                   4569:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
                   4570:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4571:          }else{
                   4572:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4573:            /* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
1.342     brouard  4574:          }
1.343     brouard  4575:        }
                   4576:        /* printf("\n"); */
1.342     brouard  4577:        /* } /\*  End debugILK *\/ */
                   4578:        fprintf(ficresilk,"\n");
                   4579:       } /* End if globpr */
1.335     brouard  4580:     } /* end of wave */
                   4581:   } /* end of individual */
                   4582:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4583: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4584:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4585:   if(globpr==0){ /* First time we count the contributions and weights */
                   4586:     gipmx=ipmx;
                   4587:     gsw=sw;
                   4588:   }
1.343     brouard  4589:   return -l;
1.126     brouard  4590: }
                   4591: 
                   4592: 
                   4593: /*************** function likelione ***********/
1.292     brouard  4594: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4595: {
                   4596:   /* This routine should help understanding what is done with 
                   4597:      the selection of individuals/waves and
                   4598:      to check the exact contribution to the likelihood.
                   4599:      Plotting could be done.
1.342     brouard  4600:   */
                   4601:   void pstamp(FILE *ficres);
1.343     brouard  4602:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4603: 
                   4604:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4605:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4606:     strcat(fileresilk,fileresu);
1.126     brouard  4607:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4608:       printf("Problem with resultfile: %s\n", fileresilk);
                   4609:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4610:     }
1.342     brouard  4611:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4612:     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");
                   4613:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4614:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4615:     for(k=1; k<=nlstate; k++) 
                   4616:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4617:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4618: 
                   4619:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4620:       for(kf=1;kf <= ncovf; kf++){
                   4621:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4622:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4623:       }
                   4624:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4625:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4626:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4627:          /* printf(" %d",ipos); */
                   4628:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4629:        }else{
                   4630:          /* printf("*"); */
                   4631:          fprintf(ficresilk,"*");
1.343     brouard  4632:        }
1.342     brouard  4633:        iposold=ipos;
                   4634:       }
                   4635:       for (kk=1; kk<=cptcovage;kk++) {
                   4636:        if(!FixedV[Tvar[Tage[kk]]]){
                   4637:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4638:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4639:        }else{
                   4640:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4641:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4642:        }
                   4643:       }
                   4644:     /* } /\* End if debugILK *\/ */
                   4645:     /* printf("\n"); */
                   4646:     fprintf(ficresilk,"\n");
                   4647:   } /* End glogpri */
1.126     brouard  4648: 
1.292     brouard  4649:   *fretone=(*func)(p);
1.126     brouard  4650:   if(*globpri !=0){
                   4651:     fclose(ficresilk);
1.205     brouard  4652:     if (mle ==0)
                   4653:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4654:     else if(mle >=1)
                   4655:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4656:     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  4657:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4658:       
1.207     brouard  4659:     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.343     brouard  4660: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4661:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4662: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4663:     
                   4664:     for (k=1; k<= nlstate ; k++) {
                   4665:       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>\n \
                   4666: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4667:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4668:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4669:        fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   4670: <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
                   4671:       }
                   4672:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4673:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4674:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4675:        /* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   4676:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4677:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4678:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4679:          if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   4680:            fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   4681: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   4682:          } /* End only for dummies time varying (single?) */
                   4683:        }else{ /* Useless product */
                   4684:          /* printf("*"); */
                   4685:          /* fprintf(ficresilk,"*"); */ 
                   4686:        }
                   4687:        iposold=ipos;
                   4688:       } /* For each time varying covariate */
                   4689:     } /* End loop on states */
                   4690: 
                   4691: /*     if(debugILK){ */
                   4692: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4693: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4694: /*     for (k=1; k<= nlstate ; k++) { */
                   4695: /*       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   4696: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
                   4697: /*     } */
                   4698: /*       } */
                   4699: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4700: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4701: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4702: /*     /\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
                   4703: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4704: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4705: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4706: /*       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
                   4707: /*         for (k=1; k<= nlstate ; k++) { */
                   4708: /*           fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   4709: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4710: /*         } /\* End state *\/ */
                   4711: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4712: /*     }else{ /\* Useless product *\/ */
                   4713: /*       /\* printf("*"); *\/ */
                   4714: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4715: /*     } */
                   4716: /*     iposold=ipos; */
                   4717: /*       } /\* For each time varying covariate *\/ */
                   4718: /*     }/\* End debugILK *\/ */
1.207     brouard  4719:     fflush(fichtm);
1.343     brouard  4720:   }/* End globpri */
1.126     brouard  4721:   return;
                   4722: }
                   4723: 
                   4724: 
                   4725: /*********** Maximum Likelihood Estimation ***************/
                   4726: 
                   4727: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4728: {
1.319     brouard  4729:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4730:   double **xi;
                   4731:   double fret;
                   4732:   double fretone; /* Only one call to likelihood */
                   4733:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4734: 
                   4735: #ifdef NLOPT
                   4736:   int creturn;
                   4737:   nlopt_opt opt;
                   4738:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4739:   double *lb;
                   4740:   double minf; /* the minimum objective value, upon return */
                   4741:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4742:   myfunc_data dinst, *d = &dinst;
                   4743: #endif
                   4744: 
                   4745: 
1.126     brouard  4746:   xi=matrix(1,npar,1,npar);
                   4747:   for (i=1;i<=npar;i++)
                   4748:     for (j=1;j<=npar;j++)
                   4749:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4750:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4751:   strcpy(filerespow,"POW_"); 
1.126     brouard  4752:   strcat(filerespow,fileres);
                   4753:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4754:     printf("Problem with resultfile: %s\n", filerespow);
                   4755:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4756:   }
                   4757:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4758:   for (i=1;i<=nlstate;i++)
                   4759:     for(j=1;j<=nlstate+ndeath;j++)
                   4760:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4761:   fprintf(ficrespow,"\n");
1.162     brouard  4762: #ifdef POWELL
1.319     brouard  4763: #ifdef LINMINORIGINAL
                   4764: #else /* LINMINORIGINAL */
                   4765:   
                   4766:   flatdir=ivector(1,npar); 
                   4767:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4768: #endif /*LINMINORIGINAL */
                   4769: 
                   4770: #ifdef FLATSUP
                   4771:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4772:   /* reorganizing p by suppressing flat directions */
                   4773:   for(i=1, jk=1; i <=nlstate; i++){
                   4774:     for(k=1; k <=(nlstate+ndeath); k++){
                   4775:       if (k != i) {
                   4776:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4777:         if(flatdir[jk]==1){
                   4778:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4779:         }
                   4780:         for(j=1; j <=ncovmodel; j++){
                   4781:           printf("%12.7f ",p[jk]);
                   4782:           jk++; 
                   4783:         }
                   4784:         printf("\n");
                   4785:       }
                   4786:     }
                   4787:   }
                   4788: /* skipping */
                   4789:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4790:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4791:     for(k=1; k <=(nlstate+ndeath); k++){
                   4792:       if (k != i) {
                   4793:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4794:         if(flatdir[jk]==1){
                   4795:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4796:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4797:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4798:             /*q[jjk]=p[jk];*/
                   4799:           }
                   4800:         }else{
                   4801:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4802:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4803:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4804:             /*q[jjk]=p[jk];*/
                   4805:           }
                   4806:         }
                   4807:         printf("\n");
                   4808:       }
                   4809:       fflush(stdout);
                   4810:     }
                   4811:   }
                   4812:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4813: #else  /* FLATSUP */
1.126     brouard  4814:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4815: #endif  /* FLATSUP */
                   4816: 
                   4817: #ifdef LINMINORIGINAL
                   4818: #else
                   4819:       free_ivector(flatdir,1,npar); 
                   4820: #endif  /* LINMINORIGINAL*/
                   4821: #endif /* POWELL */
1.126     brouard  4822: 
1.162     brouard  4823: #ifdef NLOPT
                   4824: #ifdef NEWUOA
                   4825:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4826: #else
                   4827:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4828: #endif
                   4829:   lb=vector(0,npar-1);
                   4830:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4831:   nlopt_set_lower_bounds(opt, lb);
                   4832:   nlopt_set_initial_step1(opt, 0.1);
                   4833:   
                   4834:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4835:   d->function = func;
                   4836:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4837:   nlopt_set_min_objective(opt, myfunc, d);
                   4838:   nlopt_set_xtol_rel(opt, ftol);
                   4839:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4840:     printf("nlopt failed! %d\n",creturn); 
                   4841:   }
                   4842:   else {
                   4843:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4844:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4845:     iter=1; /* not equal */
                   4846:   }
                   4847:   nlopt_destroy(opt);
                   4848: #endif
1.319     brouard  4849: #ifdef FLATSUP
                   4850:   /* npared = npar -flatd/ncovmodel; */
                   4851:   /* xired= matrix(1,npared,1,npared); */
                   4852:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4853:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4854:   /* free_matrix(xire,1,npared,1,npared); */
                   4855: #else  /* FLATSUP */
                   4856: #endif /* FLATSUP */
1.126     brouard  4857:   free_matrix(xi,1,npar,1,npar);
                   4858:   fclose(ficrespow);
1.203     brouard  4859:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4860:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4861:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4862: 
                   4863: }
                   4864: 
                   4865: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4866: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4867: {
                   4868:   double  **a,**y,*x,pd;
1.203     brouard  4869:   /* double **hess; */
1.164     brouard  4870:   int i, j;
1.126     brouard  4871:   int *indx;
                   4872: 
                   4873:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4874:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4875:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4876:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4877:   double gompertz(double p[]);
1.203     brouard  4878:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4879: 
                   4880:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4881:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4882:   for (i=1;i<=npar;i++){
1.203     brouard  4883:     printf("%d-",i);fflush(stdout);
                   4884:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4885:    
                   4886:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4887:     
                   4888:     /*  printf(" %f ",p[i]);
                   4889:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4890:   }
                   4891:   
                   4892:   for (i=1;i<=npar;i++) {
                   4893:     for (j=1;j<=npar;j++)  {
                   4894:       if (j>i) { 
1.203     brouard  4895:        printf(".%d-%d",i,j);fflush(stdout);
                   4896:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4897:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4898:        
                   4899:        hess[j][i]=hess[i][j];    
                   4900:        /*printf(" %lf ",hess[i][j]);*/
                   4901:       }
                   4902:     }
                   4903:   }
                   4904:   printf("\n");
                   4905:   fprintf(ficlog,"\n");
                   4906: 
                   4907:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4908:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4909:   
                   4910:   a=matrix(1,npar,1,npar);
                   4911:   y=matrix(1,npar,1,npar);
                   4912:   x=vector(1,npar);
                   4913:   indx=ivector(1,npar);
                   4914:   for (i=1;i<=npar;i++)
                   4915:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4916:   ludcmp(a,npar,indx,&pd);
                   4917: 
                   4918:   for (j=1;j<=npar;j++) {
                   4919:     for (i=1;i<=npar;i++) x[i]=0;
                   4920:     x[j]=1;
                   4921:     lubksb(a,npar,indx,x);
                   4922:     for (i=1;i<=npar;i++){ 
                   4923:       matcov[i][j]=x[i];
                   4924:     }
                   4925:   }
                   4926: 
                   4927:   printf("\n#Hessian matrix#\n");
                   4928:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4929:   for (i=1;i<=npar;i++) { 
                   4930:     for (j=1;j<=npar;j++) { 
1.203     brouard  4931:       printf("%.6e ",hess[i][j]);
                   4932:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4933:     }
                   4934:     printf("\n");
                   4935:     fprintf(ficlog,"\n");
                   4936:   }
                   4937: 
1.203     brouard  4938:   /* printf("\n#Covariance matrix#\n"); */
                   4939:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4940:   /* for (i=1;i<=npar;i++) {  */
                   4941:   /*   for (j=1;j<=npar;j++) {  */
                   4942:   /*     printf("%.6e ",matcov[i][j]); */
                   4943:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4944:   /*   } */
                   4945:   /*   printf("\n"); */
                   4946:   /*   fprintf(ficlog,"\n"); */
                   4947:   /* } */
                   4948: 
1.126     brouard  4949:   /* Recompute Inverse */
1.203     brouard  4950:   /* for (i=1;i<=npar;i++) */
                   4951:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4952:   /* ludcmp(a,npar,indx,&pd); */
                   4953: 
                   4954:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4955: 
                   4956:   /* for (j=1;j<=npar;j++) { */
                   4957:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4958:   /*   x[j]=1; */
                   4959:   /*   lubksb(a,npar,indx,x); */
                   4960:   /*   for (i=1;i<=npar;i++){  */
                   4961:   /*     y[i][j]=x[i]; */
                   4962:   /*     printf("%.3e ",y[i][j]); */
                   4963:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4964:   /*   } */
                   4965:   /*   printf("\n"); */
                   4966:   /*   fprintf(ficlog,"\n"); */
                   4967:   /* } */
                   4968: 
                   4969:   /* Verifying the inverse matrix */
                   4970: #ifdef DEBUGHESS
                   4971:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4972: 
1.203     brouard  4973:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4974:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4975: 
                   4976:   for (j=1;j<=npar;j++) {
                   4977:     for (i=1;i<=npar;i++){ 
1.203     brouard  4978:       printf("%.2f ",y[i][j]);
                   4979:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4980:     }
                   4981:     printf("\n");
                   4982:     fprintf(ficlog,"\n");
                   4983:   }
1.203     brouard  4984: #endif
1.126     brouard  4985: 
                   4986:   free_matrix(a,1,npar,1,npar);
                   4987:   free_matrix(y,1,npar,1,npar);
                   4988:   free_vector(x,1,npar);
                   4989:   free_ivector(indx,1,npar);
1.203     brouard  4990:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4991: 
                   4992: 
                   4993: }
                   4994: 
                   4995: /*************** hessian matrix ****************/
                   4996: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4997: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4998:   int i;
                   4999:   int l=1, lmax=20;
1.203     brouard  5000:   double k1,k2, res, fx;
1.132     brouard  5001:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5002:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5003:   int k=0,kmax=10;
                   5004:   double l1;
                   5005: 
                   5006:   fx=func(x);
                   5007:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5008:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5009:     l1=pow(10,l);
                   5010:     delts=delt;
                   5011:     for(k=1 ; k <kmax; k=k+1){
                   5012:       delt = delta*(l1*k);
                   5013:       p2[theta]=x[theta] +delt;
1.145     brouard  5014:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5015:       p2[theta]=x[theta]-delt;
                   5016:       k2=func(p2)-fx;
                   5017:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5018:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5019:       
1.203     brouard  5020: #ifdef DEBUGHESSII
1.126     brouard  5021:       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);
                   5022:       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);
                   5023: #endif
                   5024:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5025:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5026:        k=kmax;
                   5027:       }
                   5028:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5029:        k=kmax; l=lmax*10;
1.126     brouard  5030:       }
                   5031:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5032:        delts=delt;
                   5033:       }
1.203     brouard  5034:     } /* End loop k */
1.126     brouard  5035:   }
                   5036:   delti[theta]=delts;
                   5037:   return res; 
                   5038:   
                   5039: }
                   5040: 
1.203     brouard  5041: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5042: {
                   5043:   int i;
1.164     brouard  5044:   int l=1, lmax=20;
1.126     brouard  5045:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5046:   double p2[MAXPARM+1];
1.203     brouard  5047:   int k, kmax=1;
                   5048:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5049: 
                   5050:   int firstime=0;
1.203     brouard  5051:   
1.126     brouard  5052:   fx=func(x);
1.203     brouard  5053:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5054:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5055:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5056:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5057:     k1=func(p2)-fx;
                   5058:   
1.203     brouard  5059:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5060:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5061:     k2=func(p2)-fx;
                   5062:   
1.203     brouard  5063:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5064:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5065:     k3=func(p2)-fx;
                   5066:   
1.203     brouard  5067:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5068:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5069:     k4=func(p2)-fx;
1.203     brouard  5070:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5071:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5072:       firstime=1;
1.203     brouard  5073:       kmax=kmax+10;
1.208     brouard  5074:     }
                   5075:     if(kmax >=10 || firstime ==1){
1.246     brouard  5076:       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);
                   5077:       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  5078:       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);
                   5079:       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);
                   5080:     }
                   5081: #ifdef DEBUGHESSIJ
                   5082:     v1=hess[thetai][thetai];
                   5083:     v2=hess[thetaj][thetaj];
                   5084:     cv12=res;
                   5085:     /* Computing eigen value of Hessian matrix */
                   5086:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5087:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5088:     if ((lc2 <0) || (lc1 <0) ){
                   5089:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5090:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5091:       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);
                   5092:       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);
                   5093:     }
1.126     brouard  5094: #endif
                   5095:   }
                   5096:   return res;
                   5097: }
                   5098: 
1.203     brouard  5099:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5100: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5101: /* { */
                   5102: /*   int i; */
                   5103: /*   int l=1, lmax=20; */
                   5104: /*   double k1,k2,k3,k4,res,fx; */
                   5105: /*   double p2[MAXPARM+1]; */
                   5106: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5107: /*   int k=0,kmax=10; */
                   5108: /*   double l1; */
                   5109:   
                   5110: /*   fx=func(x); */
                   5111: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5112: /*     l1=pow(10,l); */
                   5113: /*     delts=delt; */
                   5114: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5115: /*       delt = delti*(l1*k); */
                   5116: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5117: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5118: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5119: /*       k1=func(p2)-fx; */
                   5120:       
                   5121: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5122: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5123: /*       k2=func(p2)-fx; */
                   5124:       
                   5125: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5126: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5127: /*       k3=func(p2)-fx; */
                   5128:       
                   5129: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5130: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5131: /*       k4=func(p2)-fx; */
                   5132: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5133: /* #ifdef DEBUGHESSIJ */
                   5134: /*       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); */
                   5135: /*       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); */
                   5136: /* #endif */
                   5137: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5138: /*     k=kmax; */
                   5139: /*       } */
                   5140: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5141: /*     k=kmax; l=lmax*10; */
                   5142: /*       } */
                   5143: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5144: /*     delts=delt; */
                   5145: /*       } */
                   5146: /*     } /\* End loop k *\/ */
                   5147: /*   } */
                   5148: /*   delti[theta]=delts; */
                   5149: /*   return res;  */
                   5150: /* } */
                   5151: 
                   5152: 
1.126     brouard  5153: /************** Inverse of matrix **************/
                   5154: void ludcmp(double **a, int n, int *indx, double *d) 
                   5155: { 
                   5156:   int i,imax,j,k; 
                   5157:   double big,dum,sum,temp; 
                   5158:   double *vv; 
                   5159:  
                   5160:   vv=vector(1,n); 
                   5161:   *d=1.0; 
                   5162:   for (i=1;i<=n;i++) { 
                   5163:     big=0.0; 
                   5164:     for (j=1;j<=n;j++) 
                   5165:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5166:     if (big == 0.0){
                   5167:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5168:       for (j=1;j<=n;j++) {
                   5169:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5170:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5171:       }
                   5172:       fflush(ficlog);
                   5173:       fclose(ficlog);
                   5174:       nrerror("Singular matrix in routine ludcmp"); 
                   5175:     }
1.126     brouard  5176:     vv[i]=1.0/big; 
                   5177:   } 
                   5178:   for (j=1;j<=n;j++) { 
                   5179:     for (i=1;i<j;i++) { 
                   5180:       sum=a[i][j]; 
                   5181:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5182:       a[i][j]=sum; 
                   5183:     } 
                   5184:     big=0.0; 
                   5185:     for (i=j;i<=n;i++) { 
                   5186:       sum=a[i][j]; 
                   5187:       for (k=1;k<j;k++) 
                   5188:        sum -= a[i][k]*a[k][j]; 
                   5189:       a[i][j]=sum; 
                   5190:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5191:        big=dum; 
                   5192:        imax=i; 
                   5193:       } 
                   5194:     } 
                   5195:     if (j != imax) { 
                   5196:       for (k=1;k<=n;k++) { 
                   5197:        dum=a[imax][k]; 
                   5198:        a[imax][k]=a[j][k]; 
                   5199:        a[j][k]=dum; 
                   5200:       } 
                   5201:       *d = -(*d); 
                   5202:       vv[imax]=vv[j]; 
                   5203:     } 
                   5204:     indx[j]=imax; 
                   5205:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5206:     if (j != n) { 
                   5207:       dum=1.0/(a[j][j]); 
                   5208:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5209:     } 
                   5210:   } 
                   5211:   free_vector(vv,1,n);  /* Doesn't work */
                   5212: ;
                   5213: } 
                   5214: 
                   5215: void lubksb(double **a, int n, int *indx, double b[]) 
                   5216: { 
                   5217:   int i,ii=0,ip,j; 
                   5218:   double sum; 
                   5219:  
                   5220:   for (i=1;i<=n;i++) { 
                   5221:     ip=indx[i]; 
                   5222:     sum=b[ip]; 
                   5223:     b[ip]=b[i]; 
                   5224:     if (ii) 
                   5225:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5226:     else if (sum) ii=i; 
                   5227:     b[i]=sum; 
                   5228:   } 
                   5229:   for (i=n;i>=1;i--) { 
                   5230:     sum=b[i]; 
                   5231:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5232:     b[i]=sum/a[i][i]; 
                   5233:   } 
                   5234: } 
                   5235: 
                   5236: void pstamp(FILE *fichier)
                   5237: {
1.196     brouard  5238:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5239: }
                   5240: 
1.297     brouard  5241: void date2dmy(double date,double *day, double *month, double *year){
                   5242:   double yp=0., yp1=0., yp2=0.;
                   5243:   
                   5244:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5245:                        fractional in yp1 */
                   5246:   *year=yp;
                   5247:   yp2=modf((yp1*12),&yp);
                   5248:   *month=yp;
                   5249:   yp1=modf((yp2*30.5),&yp);
                   5250:   *day=yp;
                   5251:   if(*day==0) *day=1;
                   5252:   if(*month==0) *month=1;
                   5253: }
                   5254: 
1.253     brouard  5255: 
                   5256: 
1.126     brouard  5257: /************ Frequencies ********************/
1.251     brouard  5258: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5259:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5260:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5261: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5262:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5263:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5264:   int iind=0, iage=0;
                   5265:   int mi; /* Effective wave */
                   5266:   int first;
                   5267:   double ***freq; /* Frequencies */
1.268     brouard  5268:   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 */
                   5269:   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  5270:   double *meanq, *stdq, *idq;
1.226     brouard  5271:   double **meanqt;
                   5272:   double *pp, **prop, *posprop, *pospropt;
                   5273:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5274:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5275:   double agebegin, ageend;
                   5276:     
                   5277:   pp=vector(1,nlstate);
1.251     brouard  5278:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5279:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5280:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5281:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5282:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5283:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5284:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5285:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5286:   strcpy(fileresp,"P_");
                   5287:   strcat(fileresp,fileresu);
                   5288:   /*strcat(fileresphtm,fileresu);*/
                   5289:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5290:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5291:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5292:     exit(0);
                   5293:   }
1.240     brouard  5294:   
1.226     brouard  5295:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5296:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5297:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5298:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5299:     fflush(ficlog);
                   5300:     exit(70); 
                   5301:   }
                   5302:   else{
                   5303:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5304: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5305: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5306:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5307:   }
1.319     brouard  5308:   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  5309:   
1.226     brouard  5310:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5311:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5312:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5313:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5314:     fflush(ficlog);
                   5315:     exit(70); 
1.240     brouard  5316:   } else{
1.226     brouard  5317:     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  5318: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5319: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5320:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5321:   }
1.319     brouard  5322:   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  5323:   
1.253     brouard  5324:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5325:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5326:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5327:   j1=0;
1.126     brouard  5328:   
1.227     brouard  5329:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5330:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5331:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5332:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5333:   
                   5334:   
1.226     brouard  5335:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5336:      reference=low_education V1=0,V2=0
                   5337:      med_educ                V1=1 V2=0, 
                   5338:      high_educ               V1=0 V2=1
1.330     brouard  5339:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5340:   */
1.249     brouard  5341:   dateintsum=0;
                   5342:   k2cpt=0;
                   5343: 
1.253     brouard  5344:   if(cptcoveff == 0 )
1.265     brouard  5345:     nl=1;  /* Constant and age model only */
1.253     brouard  5346:   else
                   5347:     nl=2;
1.265     brouard  5348: 
                   5349:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5350:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5351:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5352:    *     freq[s1][s2][iage] =0.
                   5353:    *     Loop on iind
                   5354:    *       ++freq[s1][s2][iage] weighted
                   5355:    *     end iind
                   5356:    *     if covariate and j!0
                   5357:    *       headers Variable on one line
                   5358:    *     endif cov j!=0
                   5359:    *     header of frequency table by age
                   5360:    *     Loop on age
                   5361:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5362:    *       pos+=freq[s1][s2][iage] weighted
                   5363:    *       Loop on s1 initial state
                   5364:    *         fprintf(ficresp
                   5365:    *       end s1
                   5366:    *     end age
                   5367:    *     if j!=0 computes starting values
                   5368:    *     end compute starting values
                   5369:    *   end j1
                   5370:    * end nl 
                   5371:    */
1.253     brouard  5372:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5373:     if(nj==1)
                   5374:       j=0;  /* First pass for the constant */
1.265     brouard  5375:     else{
1.335     brouard  5376:       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  5377:     }
1.251     brouard  5378:     first=1;
1.332     brouard  5379:     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  5380:       posproptt=0.;
1.330     brouard  5381:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5382:        scanf("%d", i);*/
                   5383:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5384:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5385:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5386:            freq[i][s2][m]=0;
1.251     brouard  5387:       
                   5388:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5389:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5390:          prop[i][m]=0;
                   5391:        posprop[i]=0;
                   5392:        pospropt[i]=0;
                   5393:       }
1.283     brouard  5394:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5395:         idq[z1]=0.;
                   5396:         meanq[z1]=0.;
                   5397:         stdq[z1]=0.;
1.283     brouard  5398:       }
                   5399:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5400:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5401:       /*         meanqt[m][z1]=0.; */
                   5402:       /*       } */
                   5403:       /* }       */
1.251     brouard  5404:       /* dateintsum=0; */
                   5405:       /* k2cpt=0; */
                   5406:       
1.265     brouard  5407:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5408:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5409:        bool=1;
                   5410:        if(j !=0){
                   5411:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5412:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5413:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5414:                /* if(Tvaraff[z1] ==-20){ */
                   5415:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5416:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5417:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5418:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5419:                /* 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); */
                   5420:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5421:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5422:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5423:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5424:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5425:                  /* 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", */
                   5426:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5427:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5428:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5429:                } /* Onlyf fixed */
                   5430:              } /* end z1 */
1.335     brouard  5431:            } /* cptcoveff > 0 */
1.251     brouard  5432:          } /* end any */
                   5433:        }/* end j==0 */
1.265     brouard  5434:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5435:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5436:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5437:            m=mw[mi][iind];
                   5438:            if(j!=0){
                   5439:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5440:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5441:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5442:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5443:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5444:                    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  5445:                                                                                      value is -1, we don't select. It differs from the 
                   5446:                                                                                      constant and age model which counts them. */
                   5447:                      bool=0; /* not selected */
                   5448:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5449:                    /* i1=Tvaraff[z1]; */
                   5450:                    /* i2=TnsdVar[i1]; */
                   5451:                    /* i3=nbcode[i1][i2]; */
                   5452:                    /* i4=covar[i1][iind]; */
                   5453:                    /* if(i4 != i3){ */
                   5454:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5455:                      bool=0;
                   5456:                    }
                   5457:                  }
                   5458:                }
                   5459:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5460:            } /* end j==0 */
                   5461:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5462:            if(bool==1){ /*Selected */
1.251     brouard  5463:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5464:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5465:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5466:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5467:              if(m >=firstpass && m <=lastpass){
                   5468:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5469:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5470:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5471:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5472:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5473:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5474:                if (m<lastpass) {
                   5475:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5476:                  /*   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]); */
                   5477:                  if(s[m][iind]==-1)
                   5478:                    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.));
                   5479:                  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  5480:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5481:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5482:                      idq[z1]=idq[z1]+weight[iind];
                   5483:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5484:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5485:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5486:                    }
1.284     brouard  5487:                  }
1.251     brouard  5488:                  /* if((int)agev[m][iind] == 55) */
                   5489:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5490:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5491:                  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  5492:                }
1.251     brouard  5493:              } /* end if between passes */  
                   5494:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5495:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5496:                k2cpt++;
                   5497:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5498:              }
1.251     brouard  5499:            }else{
                   5500:              bool=1;
                   5501:            }/* end bool 2 */
                   5502:          } /* end m */
1.284     brouard  5503:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5504:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5505:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5506:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5507:          /* } */
1.251     brouard  5508:        } /* end bool */
                   5509:       } /* end iind = 1 to imx */
1.319     brouard  5510:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5511:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5512:       
                   5513:       
                   5514:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5515:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5516:         pstamp(ficresp);
1.335     brouard  5517:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5518:         pstamp(ficresp);
1.251     brouard  5519:        printf( "\n#********** Variable "); 
                   5520:        fprintf(ficresp, "\n#********** Variable "); 
                   5521:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5522:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5523:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5524:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5525:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5526:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5527:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5528:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5529:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5530:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5531:          }else{
1.330     brouard  5532:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5533:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5534:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5535:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5536:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5537:          }
                   5538:        }
                   5539:        printf( "**********\n#");
                   5540:        fprintf(ficresp, "**********\n#");
                   5541:        fprintf(ficresphtm, "**********</h3>\n");
                   5542:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5543:        fprintf(ficlog, "**********\n");
                   5544:       }
1.284     brouard  5545:       /*
                   5546:        Printing means of quantitative variables if any
                   5547:       */
                   5548:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5549:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5550:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5551:        if(weightopt==1){
                   5552:          printf(" Weighted mean and standard deviation of");
                   5553:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5554:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5555:        }
1.311     brouard  5556:        /* mu = \frac{w x}{\sum w}
                   5557:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5558:        */
                   5559:        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]));
                   5560:        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]));
                   5561:        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  5562:       }
                   5563:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5564:       /*       for(m=1;m<=lastpass;m++){ */
                   5565:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5566:       /*   } */
                   5567:       /* } */
1.283     brouard  5568: 
1.251     brouard  5569:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5570:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5571:         fprintf(ficresp, " Age");
1.335     brouard  5572:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5573:          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]]);
                   5574:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5575:        }
1.251     brouard  5576:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5577:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5578:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5579:       }
1.335     brouard  5580:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5581:       fprintf(ficresphtm, "\n");
                   5582:       
                   5583:       /* Header of frequency table by age */
                   5584:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5585:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5586:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5587:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5588:          if(s2!=0 && m!=0)
                   5589:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5590:        }
1.226     brouard  5591:       }
1.251     brouard  5592:       fprintf(ficresphtmfr, "\n");
                   5593:     
                   5594:       /* For each age */
                   5595:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5596:        fprintf(ficresphtm,"<tr>");
                   5597:        if(iage==iagemax+1){
                   5598:          fprintf(ficlog,"1");
                   5599:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5600:        }else if(iage==iagemax+2){
                   5601:          fprintf(ficlog,"0");
                   5602:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5603:        }else if(iage==iagemax+3){
                   5604:          fprintf(ficlog,"Total");
                   5605:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5606:        }else{
1.240     brouard  5607:          if(first==1){
1.251     brouard  5608:            first=0;
                   5609:            printf("See log file for details...\n");
                   5610:          }
                   5611:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5612:          fprintf(ficlog,"Age %d", iage);
                   5613:        }
1.265     brouard  5614:        for(s1=1; s1 <=nlstate ; s1++){
                   5615:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5616:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5617:        }
1.265     brouard  5618:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5619:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5620:            pos += freq[s1][m][iage];
                   5621:          if(pp[s1]>=1.e-10){
1.251     brouard  5622:            if(first==1){
1.265     brouard  5623:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5624:            }
1.265     brouard  5625:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5626:          }else{
                   5627:            if(first==1)
1.265     brouard  5628:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5629:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5630:          }
                   5631:        }
                   5632:       
1.265     brouard  5633:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5634:          /* posprop[s1]=0; */
                   5635:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5636:            pp[s1] += freq[s1][m][iage];
                   5637:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5638:       
                   5639:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5640:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5641:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5642:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5643:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5644:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5645:        }
                   5646:        
                   5647:        /* Writing ficresp */
1.335     brouard  5648:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5649:           if( iage <= iagemax){
                   5650:            fprintf(ficresp," %d",iage);
                   5651:           }
                   5652:         }else if( nj==2){
                   5653:           if( iage <= iagemax){
                   5654:            fprintf(ficresp," %d",iage);
1.335     brouard  5655:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5656:           }
1.240     brouard  5657:        }
1.265     brouard  5658:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5659:          if(pos>=1.e-5){
1.251     brouard  5660:            if(first==1)
1.265     brouard  5661:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5662:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5663:          }else{
                   5664:            if(first==1)
1.265     brouard  5665:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5666:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5667:          }
                   5668:          if( iage <= iagemax){
                   5669:            if(pos>=1.e-5){
1.335     brouard  5670:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5671:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5672:               }else if( nj==2){
                   5673:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5674:               }
                   5675:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5676:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5677:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5678:            } else{
1.335     brouard  5679:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5680:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5681:            }
1.240     brouard  5682:          }
1.265     brouard  5683:          pospropt[s1] +=posprop[s1];
                   5684:        } /* end loop s1 */
1.251     brouard  5685:        /* pospropt=0.; */
1.265     brouard  5686:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5687:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5688:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5689:              if(first==1){
1.265     brouard  5690:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5691:              }
1.265     brouard  5692:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5693:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5694:            }
1.265     brouard  5695:            if(s1!=0 && m!=0)
                   5696:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5697:          }
1.265     brouard  5698:        } /* end loop s1 */
1.251     brouard  5699:        posproptt=0.; 
1.265     brouard  5700:        for(s1=1; s1 <=nlstate; s1++){
                   5701:          posproptt += pospropt[s1];
1.251     brouard  5702:        }
                   5703:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5704:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5705:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5706:          if(iage <= iagemax)
                   5707:            fprintf(ficresp,"\n");
1.240     brouard  5708:        }
1.251     brouard  5709:        if(first==1)
                   5710:          printf("Others in log...\n");
                   5711:        fprintf(ficlog,"\n");
                   5712:       } /* end loop age iage */
1.265     brouard  5713:       
1.251     brouard  5714:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5715:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5716:        if(posproptt < 1.e-5){
1.265     brouard  5717:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5718:        }else{
1.265     brouard  5719:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5720:        }
1.226     brouard  5721:       }
1.251     brouard  5722:       fprintf(ficresphtm,"</tr>\n");
                   5723:       fprintf(ficresphtm,"</table>\n");
                   5724:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5725:       if(posproptt < 1.e-5){
1.251     brouard  5726:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5727:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5728:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5729:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5730:        invalidvarcomb[j1]=1;
1.226     brouard  5731:       }else{
1.338     brouard  5732:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5733:        invalidvarcomb[j1]=0;
1.226     brouard  5734:       }
1.251     brouard  5735:       fprintf(ficresphtmfr,"</table>\n");
                   5736:       fprintf(ficlog,"\n");
                   5737:       if(j!=0){
                   5738:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5739:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5740:          for(k=1; k <=(nlstate+ndeath); k++){
                   5741:            if (k != i) {
1.265     brouard  5742:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5743:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5744:                  if(j1==1){ /* All dummy covariates to zero */
                   5745:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5746:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5747:                    printf("%d%d ",i,k);
                   5748:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5749:                    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]));
                   5750:                    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]));
                   5751:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5752:                  }
1.253     brouard  5753:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5754:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5755:                    x[iage]= (double)iage;
                   5756:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5757:                    /* 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  5758:                  }
1.268     brouard  5759:                  /* Some are not finite, but linreg will ignore these ages */
                   5760:                  no=0;
1.253     brouard  5761:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5762:                  pstart[s1]=b;
                   5763:                  pstart[s1-1]=a;
1.252     brouard  5764:                }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 */ 
                   5765:                  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]);
                   5766:                  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  5767:                  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  5768:                  printf("%d%d ",i,k);
                   5769:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5770:                  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  5771:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5772:                  ;
                   5773:                }
                   5774:                /* printf("%12.7f )", param[i][jj][k]); */
                   5775:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5776:                s1++; 
1.251     brouard  5777:              } /* end jj */
                   5778:            } /* end k!= i */
                   5779:          } /* end k */
1.265     brouard  5780:        } /* end i, s1 */
1.251     brouard  5781:       } /* end j !=0 */
                   5782:     } /* end selected combination of covariate j1 */
                   5783:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5784:       printf("#Freqsummary: Starting values for the constants:\n");
                   5785:       fprintf(ficlog,"\n");
1.265     brouard  5786:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5787:        for(k=1; k <=(nlstate+ndeath); k++){
                   5788:          if (k != i) {
                   5789:            printf("%d%d ",i,k);
                   5790:            fprintf(ficlog,"%d%d ",i,k);
                   5791:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5792:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5793:              if(jj==1){ /* Age has to be done */
1.265     brouard  5794:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5795:                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]));
                   5796:                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  5797:              }
                   5798:              /* printf("%12.7f )", param[i][jj][k]); */
                   5799:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5800:              s1++; 
1.250     brouard  5801:            }
1.251     brouard  5802:            printf("\n");
                   5803:            fprintf(ficlog,"\n");
1.250     brouard  5804:          }
                   5805:        }
1.284     brouard  5806:       } /* end of state i */
1.251     brouard  5807:       printf("#Freqsummary\n");
                   5808:       fprintf(ficlog,"\n");
1.265     brouard  5809:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5810:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5811:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5812:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5813:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5814:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5815:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5816:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5817:          /* } */
                   5818:        }
1.265     brouard  5819:       } /* end loop s1 */
1.251     brouard  5820:       
                   5821:       printf("\n");
                   5822:       fprintf(ficlog,"\n");
                   5823:     } /* end j=0 */
1.249     brouard  5824:   } /* end j */
1.252     brouard  5825: 
1.253     brouard  5826:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5827:     for(i=1, jk=1; i <=nlstate; i++){
                   5828:       for(j=1; j <=nlstate+ndeath; j++){
                   5829:        if(j!=i){
                   5830:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5831:          printf("%1d%1d",i,j);
                   5832:          fprintf(ficparo,"%1d%1d",i,j);
                   5833:          for(k=1; k<=ncovmodel;k++){
                   5834:            /*    printf(" %lf",param[i][j][k]); */
                   5835:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5836:            p[jk]=pstart[jk];
                   5837:            printf(" %f ",pstart[jk]);
                   5838:            fprintf(ficparo," %f ",pstart[jk]);
                   5839:            jk++;
                   5840:          }
                   5841:          printf("\n");
                   5842:          fprintf(ficparo,"\n");
                   5843:        }
                   5844:       }
                   5845:     }
                   5846:   } /* end mle=-2 */
1.226     brouard  5847:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5848:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5849:   
1.226     brouard  5850:   fclose(ficresp);
                   5851:   fclose(ficresphtm);
                   5852:   fclose(ficresphtmfr);
1.283     brouard  5853:   free_vector(idq,1,nqfveff);
1.226     brouard  5854:   free_vector(meanq,1,nqfveff);
1.284     brouard  5855:   free_vector(stdq,1,nqfveff);
1.226     brouard  5856:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5857:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5858:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5859:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5860:   free_vector(pospropt,1,nlstate);
                   5861:   free_vector(posprop,1,nlstate);
1.251     brouard  5862:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5863:   free_vector(pp,1,nlstate);
                   5864:   /* End of freqsummary */
                   5865: }
1.126     brouard  5866: 
1.268     brouard  5867: /* Simple linear regression */
                   5868: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5869: 
                   5870:   /* y=a+bx regression */
                   5871:   double   sumx = 0.0;                        /* sum of x                      */
                   5872:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5873:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5874:   double   sumy = 0.0;                        /* sum of y                      */
                   5875:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5876:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5877:   double yhat;
                   5878:   
                   5879:   double denom=0;
                   5880:   int i;
                   5881:   int ne=*no;
                   5882:   
                   5883:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5884:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5885:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5886:       continue;
                   5887:     }
                   5888:     ne=ne+1;
                   5889:     sumx  += x[i];       
                   5890:     sumx2 += x[i]*x[i];  
                   5891:     sumxy += x[i] * y[i];
                   5892:     sumy  += y[i];      
                   5893:     sumy2 += y[i]*y[i]; 
                   5894:     denom = (ne * sumx2 - sumx*sumx);
                   5895:     /* 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); */
                   5896:   } 
                   5897:   
                   5898:   denom = (ne * sumx2 - sumx*sumx);
                   5899:   if (denom == 0) {
                   5900:     // vertical, slope m is infinity
                   5901:     *b = INFINITY;
                   5902:     *a = 0;
                   5903:     if (r) *r = 0;
                   5904:     return 1;
                   5905:   }
                   5906:   
                   5907:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5908:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5909:   if (r!=NULL) {
                   5910:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5911:       sqrt((sumx2 - sumx*sumx/ne) *
                   5912:           (sumy2 - sumy*sumy/ne));
                   5913:   }
                   5914:   *no=ne;
                   5915:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5916:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5917:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5918:       continue;
                   5919:     }
                   5920:     ne=ne+1;
                   5921:     yhat = y[i] - *a -*b* x[i];
                   5922:     sume2  += yhat * yhat ;       
                   5923:     
                   5924:     denom = (ne * sumx2 - sumx*sumx);
                   5925:     /* 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); */
                   5926:   } 
                   5927:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5928:   *sa= *sb * sqrt(sumx2/ne);
                   5929:   
                   5930:   return 0; 
                   5931: }
                   5932: 
1.126     brouard  5933: /************ Prevalence ********************/
1.227     brouard  5934: 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)
                   5935: {  
                   5936:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5937:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5938:      We still use firstpass and lastpass as another selection.
                   5939:   */
1.126     brouard  5940:  
1.227     brouard  5941:   int i, m, jk, j1, bool, z1,j, iv;
                   5942:   int mi; /* Effective wave */
                   5943:   int iage;
                   5944:   double agebegin, ageend;
                   5945: 
                   5946:   double **prop;
                   5947:   double posprop; 
                   5948:   double  y2; /* in fractional years */
                   5949:   int iagemin, iagemax;
                   5950:   int first; /** to stop verbosity which is redirected to log file */
                   5951: 
                   5952:   iagemin= (int) agemin;
                   5953:   iagemax= (int) agemax;
                   5954:   /*pp=vector(1,nlstate);*/
1.251     brouard  5955:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5956:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5957:   j1=0;
1.222     brouard  5958:   
1.227     brouard  5959:   /*j=cptcoveff;*/
                   5960:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5961:   
1.288     brouard  5962:   first=0;
1.335     brouard  5963:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5964:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5965:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5966:        prop[i][iage]=0.0;
                   5967:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5968:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5969:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5970:     
                   5971:     for (i=1; i<=imx; i++) { /* Each individual */
                   5972:       bool=1;
                   5973:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5974:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5975:        m=mw[mi][i];
                   5976:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5977:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5978:        for (z1=1; z1<=cptcoveff; z1++){
                   5979:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5980:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5981:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5982:              bool=0;
                   5983:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5984:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5985:              bool=0;
                   5986:            }
                   5987:        }
                   5988:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5989:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5990:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5991:          if(m >=firstpass && m <=lastpass){
                   5992:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5993:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5994:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5995:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5996:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5997:                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); 
                   5998:                exit(1);
                   5999:              }
                   6000:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6001:                /*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]]);*/
                   6002:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6003:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6004:              } /* end valid statuses */ 
                   6005:            } /* end selection of dates */
                   6006:          } /* end selection of waves */
                   6007:        } /* end bool */
                   6008:       } /* end wave */
                   6009:     } /* end individual */
                   6010:     for(i=iagemin; i <= iagemax+3; i++){  
                   6011:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6012:        posprop += prop[jk][i]; 
                   6013:       } 
                   6014:       
                   6015:       for(jk=1; jk <=nlstate ; jk++){      
                   6016:        if( i <=  iagemax){ 
                   6017:          if(posprop>=1.e-5){ 
                   6018:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6019:          } else{
1.288     brouard  6020:            if(!first){
                   6021:              first=1;
1.266     brouard  6022:              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]);
                   6023:            }else{
1.288     brouard  6024:              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  6025:            }
                   6026:          }
                   6027:        } 
                   6028:       }/* end jk */ 
                   6029:     }/* end i */ 
1.222     brouard  6030:      /*} *//* end i1 */
1.227     brouard  6031:   } /* end j1 */
1.222     brouard  6032:   
1.227     brouard  6033:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6034:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6035:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6036: }  /* End of prevalence */
1.126     brouard  6037: 
                   6038: /************* Waves Concatenation ***************/
                   6039: 
                   6040: 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)
                   6041: {
1.298     brouard  6042:   /* 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  6043:      Death is a valid wave (if date is known).
                   6044:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6045:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6046:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6047:   */
1.126     brouard  6048: 
1.224     brouard  6049:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6050:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6051:      double sum=0., jmean=0.;*/
1.224     brouard  6052:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6053:   int j, k=0,jk, ju, jl;
                   6054:   double sum=0.;
                   6055:   first=0;
1.214     brouard  6056:   firstwo=0;
1.217     brouard  6057:   firsthree=0;
1.218     brouard  6058:   firstfour=0;
1.164     brouard  6059:   jmin=100000;
1.126     brouard  6060:   jmax=-1;
                   6061:   jmean=0.;
1.224     brouard  6062: 
                   6063: /* Treating live states */
1.214     brouard  6064:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6065:     mi=0;  /* First valid wave */
1.227     brouard  6066:     mli=0; /* Last valid wave */
1.309     brouard  6067:     m=firstpass;  /* Loop on waves */
                   6068:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6069:       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 */
                   6070:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6071:       }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  6072:        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  6073:        mli=m;
1.224     brouard  6074:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6075:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6076:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6077:       }
1.309     brouard  6078:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6079: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6080:        break;
1.224     brouard  6081: #else
1.317     brouard  6082:        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  6083:          if(firsthree == 0){
1.302     brouard  6084:            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  6085:            firsthree=1;
1.317     brouard  6086:          }else if(firsthree >=1 && firsthree < 10){
                   6087:            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);
                   6088:            firsthree++;
                   6089:          }else if(firsthree == 10){
                   6090:            printf("Information, too many Information flags: no more reported to log either\n");
                   6091:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6092:            firsthree++;
                   6093:          }else{
                   6094:            firsthree++;
1.227     brouard  6095:          }
1.309     brouard  6096:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6097:          mli=m;
                   6098:        }
                   6099:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6100:          nbwarn++;
1.309     brouard  6101:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6102:            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);
                   6103:            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);
                   6104:          }
                   6105:          break;
                   6106:        }
                   6107:        break;
1.224     brouard  6108: #endif
1.227     brouard  6109:       }/* End m >= lastpass */
1.126     brouard  6110:     }/* end while */
1.224     brouard  6111: 
1.227     brouard  6112:     /* 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  6113:     /* After last pass */
1.224     brouard  6114: /* Treating death states */
1.214     brouard  6115:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6116:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6117:       /* } */
1.126     brouard  6118:       mi++;    /* Death is another wave */
                   6119:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6120:       /* Only death is a correct wave */
1.126     brouard  6121:       mw[mi][i]=m;
1.257     brouard  6122:     } /* else not in a death state */
1.224     brouard  6123: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6124:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6125:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6126:        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  6127:          nbwarn++;
                   6128:          if(firstfiv==0){
1.309     brouard  6129:            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  6130:            firstfiv=1;
                   6131:          }else{
1.309     brouard  6132:            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  6133:          }
1.309     brouard  6134:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6135:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6136:          nberr++;
                   6137:          if(firstwo==0){
1.309     brouard  6138:            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  6139:            firstwo=1;
                   6140:          }
1.309     brouard  6141:          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  6142:        }
1.257     brouard  6143:       }else{ /* if date of interview is unknown */
1.227     brouard  6144:        /* death is known but not confirmed by death status at any wave */
                   6145:        if(firstfour==0){
1.309     brouard  6146:          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  6147:          firstfour=1;
                   6148:        }
1.309     brouard  6149:        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  6150:       }
1.224     brouard  6151:     } /* end if date of death is known */
                   6152: #endif
1.309     brouard  6153:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6154:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6155:     if(mi==0){
                   6156:       nbwarn++;
                   6157:       if(first==0){
1.227     brouard  6158:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6159:        first=1;
1.126     brouard  6160:       }
                   6161:       if(first==1){
1.227     brouard  6162:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6163:       }
                   6164:     } /* end mi==0 */
                   6165:   } /* End individuals */
1.214     brouard  6166:   /* wav and mw are no more changed */
1.223     brouard  6167:        
1.317     brouard  6168:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6169:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6170: 
                   6171: 
1.126     brouard  6172:   for(i=1; i<=imx; i++){
                   6173:     for(mi=1; mi<wav[i];mi++){
                   6174:       if (stepm <=0)
1.227     brouard  6175:        dh[mi][i]=1;
1.126     brouard  6176:       else{
1.260     brouard  6177:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6178:          if (agedc[i] < 2*AGESUP) {
                   6179:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6180:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6181:            else if(j<0){
                   6182:              nberr++;
                   6183:              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]);
                   6184:              j=1; /* Temporary Dangerous patch */
                   6185:              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);
                   6186:              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]);
                   6187:              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);
                   6188:            }
                   6189:            k=k+1;
                   6190:            if (j >= jmax){
                   6191:              jmax=j;
                   6192:              ijmax=i;
                   6193:            }
                   6194:            if (j <= jmin){
                   6195:              jmin=j;
                   6196:              ijmin=i;
                   6197:            }
                   6198:            sum=sum+j;
                   6199:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6200:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6201:          }
                   6202:        }
                   6203:        else{
                   6204:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6205: /*       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  6206:                                        
1.227     brouard  6207:          k=k+1;
                   6208:          if (j >= jmax) {
                   6209:            jmax=j;
                   6210:            ijmax=i;
                   6211:          }
                   6212:          else if (j <= jmin){
                   6213:            jmin=j;
                   6214:            ijmin=i;
                   6215:          }
                   6216:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6217:          /*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]);*/
                   6218:          if(j<0){
                   6219:            nberr++;
                   6220:            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]);
                   6221:            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]);
                   6222:          }
                   6223:          sum=sum+j;
                   6224:        }
                   6225:        jk= j/stepm;
                   6226:        jl= j -jk*stepm;
                   6227:        ju= j -(jk+1)*stepm;
                   6228:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6229:          if(jl==0){
                   6230:            dh[mi][i]=jk;
                   6231:            bh[mi][i]=0;
                   6232:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6233:                  * to avoid the price of an extra matrix product in likelihood */
                   6234:            dh[mi][i]=jk+1;
                   6235:            bh[mi][i]=ju;
                   6236:          }
                   6237:        }else{
                   6238:          if(jl <= -ju){
                   6239:            dh[mi][i]=jk;
                   6240:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6241:                                 * is higher than the multiple of stepm and negative otherwise.
                   6242:                                 */
                   6243:          }
                   6244:          else{
                   6245:            dh[mi][i]=jk+1;
                   6246:            bh[mi][i]=ju;
                   6247:          }
                   6248:          if(dh[mi][i]==0){
                   6249:            dh[mi][i]=1; /* At least one step */
                   6250:            bh[mi][i]=ju; /* At least one step */
                   6251:            /*  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);*/
                   6252:          }
                   6253:        } /* end if mle */
1.126     brouard  6254:       }
                   6255:     } /* end wave */
                   6256:   }
                   6257:   jmean=sum/k;
                   6258:   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  6259:   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  6260: }
1.126     brouard  6261: 
                   6262: /*********** Tricode ****************************/
1.220     brouard  6263:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6264:  {
                   6265:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6266:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6267:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6268:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6269:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6270:     */
1.130     brouard  6271: 
1.242     brouard  6272:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6273:    int modmaxcovj=0; /* Modality max of covariates j */
                   6274:    int cptcode=0; /* Modality max of covariates j */
                   6275:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6276: 
                   6277: 
1.242     brouard  6278:    /* cptcoveff=0;  */
                   6279:    /* *cptcov=0; */
1.126     brouard  6280:  
1.242     brouard  6281:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6282:    for (k=1; k <= maxncov; k++)
                   6283:      for(j=1; j<=2; j++)
                   6284:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6285: 
1.242     brouard  6286:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6287:    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  6288:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6289:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6290:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6291:        switch(Fixed[k]) {
                   6292:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6293:         modmaxcovj=0;
                   6294:         modmincovj=0;
1.242     brouard  6295:         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.339     brouard  6296:           /* printf("Waiting for error tricode Tvar[%d]=%d i=%d (int)(covar[Tvar[k]][i]=%d\n",k,Tvar[k], i, (int)(covar[Tvar[k]][i])); */
1.242     brouard  6297:           ij=(int)(covar[Tvar[k]][i]);
                   6298:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6299:            * If product of Vn*Vm, still boolean *:
                   6300:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6301:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6302:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6303:              modality of the nth covariate of individual i. */
                   6304:           if (ij > modmaxcovj)
                   6305:             modmaxcovj=ij; 
                   6306:           else if (ij < modmincovj) 
                   6307:             modmincovj=ij; 
1.287     brouard  6308:           if (ij <0 || ij >1 ){
1.311     brouard  6309:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6310:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6311:             fflush(ficlog);
                   6312:             exit(1);
1.287     brouard  6313:           }
                   6314:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6315:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6316:             exit(1);
                   6317:           }else
                   6318:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6319:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6320:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6321:           /* getting the maximum value of the modality of the covariate
                   6322:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6323:              female ies 1, then modmaxcovj=1.
                   6324:           */
                   6325:         } /* end for loop on individuals i */
                   6326:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6327:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6328:         cptcode=modmaxcovj;
                   6329:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6330:         /*for (i=0; i<=cptcode; i++) {*/
                   6331:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6332:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6333:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6334:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6335:             if( j != -1){
                   6336:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6337:                                  covariate for which somebody answered excluding 
                   6338:                                  undefined. Usually 2: 0 and 1. */
                   6339:             }
                   6340:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6341:                                     covariate for which somebody answered including 
                   6342:                                     undefined. Usually 3: -1, 0 and 1. */
                   6343:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6344:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6345:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6346:                        
1.242     brouard  6347:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6348:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6349:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6350:         /* modmincovj=3; modmaxcovj = 7; */
                   6351:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6352:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6353:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6354:         /* nbcode[Tvar[j]][ij]=k; */
                   6355:         /* nbcode[Tvar[j]][1]=0; */
                   6356:         /* nbcode[Tvar[j]][2]=1; */
                   6357:         /* nbcode[Tvar[j]][3]=2; */
                   6358:         /* To be continued (not working yet). */
                   6359:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6360: 
                   6361:         /* 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*/
                   6362:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6363:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6364:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6365:         /*, could be restored in the future */
                   6366:         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  6367:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6368:             break;
                   6369:           }
                   6370:           ij++;
1.287     brouard  6371:           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  6372:           cptcode = ij; /* New max modality for covar j */
                   6373:         } /* end of loop on modality i=-1 to 1 or more */
                   6374:         break;
                   6375:        case 1: /* Testing on varying covariate, could be simple and
                   6376:                * should look at waves or product of fixed *
                   6377:                * varying. No time to test -1, assuming 0 and 1 only */
                   6378:         ij=0;
                   6379:         for(i=0; i<=1;i++){
                   6380:           nbcode[Tvar[k]][++ij]=i;
                   6381:         }
                   6382:         break;
                   6383:        default:
                   6384:         break;
                   6385:        } /* end switch */
                   6386:      } /* end dummy test */
1.342     brouard  6387:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6388:        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  6389:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6390:           printf("Error k=%d \n",k);
                   6391:           exit(1);
                   6392:         }
1.311     brouard  6393:         if(isnan(covar[Tvar[k]][i])){
                   6394:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6395:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6396:           fflush(ficlog);
                   6397:           exit(1);
                   6398:          }
                   6399:        }
1.335     brouard  6400:      } /* end Quanti */
1.287     brouard  6401:    } /* 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  6402:   
                   6403:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6404:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6405:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6406:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6407:      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 */ 
                   6408:      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 */
                   6409:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6410:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6411:   
                   6412:    ij=0;
                   6413:    /* 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  6414:    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 */
                   6415:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6416:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6417:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6418:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6419:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6420:        /* 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  6421:        /* If product not in single variable we don't print results */
                   6422:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6423:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6424:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6425:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6426:        /* ij            1    2                                            3  */  
                   6427:        /* Tvaraff[ij]=  4    3                                            1  */
                   6428:        /* Tmodelind[ij]=2    3                                            9  */
                   6429:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6430:        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*/
                   6431:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6432:        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 */
                   6433:        if(Fixed[k]!=0)
                   6434:         anyvaryingduminmodel=1;
                   6435:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6436:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6437:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6438:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6439:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6440:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6441:      } 
                   6442:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6443:    /* ij--; */
                   6444:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6445:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6446:                * because they can be excluded from the model and real
                   6447:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6448:    for(j=ij+1; j<= cptcovt; j++){
                   6449:      Tvaraff[j]=0;
                   6450:      Tmodelind[j]=0;
                   6451:    }
                   6452:    for(j=ntveff+1; j<= cptcovt; j++){
                   6453:      TmodelInvind[j]=0;
                   6454:    }
                   6455:    /* To be sorted */
                   6456:    ;
                   6457:  }
1.126     brouard  6458: 
1.145     brouard  6459: 
1.126     brouard  6460: /*********** Health Expectancies ****************/
                   6461: 
1.235     brouard  6462:  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  6463: 
                   6464: {
                   6465:   /* Health expectancies, no variances */
1.329     brouard  6466:   /* cij is the combination in the list of combination of dummy covariates */
                   6467:   /* strstart is a string of time at start of computing */
1.164     brouard  6468:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6469:   int nhstepma, nstepma; /* Decreasing with age */
                   6470:   double age, agelim, hf;
                   6471:   double ***p3mat;
                   6472:   double eip;
                   6473: 
1.238     brouard  6474:   /* pstamp(ficreseij); */
1.126     brouard  6475:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6476:   fprintf(ficreseij,"# Age");
                   6477:   for(i=1; i<=nlstate;i++){
                   6478:     for(j=1; j<=nlstate;j++){
                   6479:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6480:     }
                   6481:     fprintf(ficreseij," e%1d. ",i);
                   6482:   }
                   6483:   fprintf(ficreseij,"\n");
                   6484: 
                   6485:   
                   6486:   if(estepm < stepm){
                   6487:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6488:   }
                   6489:   else  hstepm=estepm;   
                   6490:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6491:    * This is mainly to measure the difference between two models: for example
                   6492:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6493:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6494:    * progression in between and thus overestimating or underestimating according
                   6495:    * to the curvature of the survival function. If, for the same date, we 
                   6496:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6497:    * to compare the new estimate of Life expectancy with the same linear 
                   6498:    * hypothesis. A more precise result, taking into account a more precise
                   6499:    * curvature will be obtained if estepm is as small as stepm. */
                   6500: 
                   6501:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6502:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6503:      nhstepm is the number of hstepm from age to agelim 
                   6504:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6505:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6506:      and note for a fixed period like estepm months */
                   6507:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6508:      survival function given by stepm (the optimization length). Unfortunately it
                   6509:      means that if the survival funtion is printed only each two years of age and if
                   6510:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6511:      results. So we changed our mind and took the option of the best precision.
                   6512:   */
                   6513:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6514: 
                   6515:   agelim=AGESUP;
                   6516:   /* If stepm=6 months */
                   6517:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6518:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6519:     
                   6520: /* nhstepm age range expressed in number of stepm */
                   6521:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6522:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6523:   /* if (stepm >= YEARM) hstepm=1;*/
                   6524:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6525:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6526: 
                   6527:   for (age=bage; age<=fage; age ++){ 
                   6528:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6529:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6530:     /* if (stepm >= YEARM) hstepm=1;*/
                   6531:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6532: 
                   6533:     /* If stepm=6 months */
                   6534:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6535:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6536:     /* 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  6537:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6538:     
                   6539:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6540:     
                   6541:     printf("%d|",(int)age);fflush(stdout);
                   6542:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6543:     
                   6544:     /* Computing expectancies */
                   6545:     for(i=1; i<=nlstate;i++)
                   6546:       for(j=1; j<=nlstate;j++)
                   6547:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6548:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6549:          
                   6550:          /* 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]);*/
                   6551: 
                   6552:        }
                   6553: 
                   6554:     fprintf(ficreseij,"%3.0f",age );
                   6555:     for(i=1; i<=nlstate;i++){
                   6556:       eip=0;
                   6557:       for(j=1; j<=nlstate;j++){
                   6558:        eip +=eij[i][j][(int)age];
                   6559:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6560:       }
                   6561:       fprintf(ficreseij,"%9.4f", eip );
                   6562:     }
                   6563:     fprintf(ficreseij,"\n");
                   6564:     
                   6565:   }
                   6566:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6567:   printf("\n");
                   6568:   fprintf(ficlog,"\n");
                   6569:   
                   6570: }
                   6571: 
1.235     brouard  6572:  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  6573: 
                   6574: {
                   6575:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6576:      to initial status i, ei. .
1.126     brouard  6577:   */
1.336     brouard  6578:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6579:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6580:   int nhstepma, nstepma; /* Decreasing with age */
                   6581:   double age, agelim, hf;
                   6582:   double ***p3matp, ***p3matm, ***varhe;
                   6583:   double **dnewm,**doldm;
                   6584:   double *xp, *xm;
                   6585:   double **gp, **gm;
                   6586:   double ***gradg, ***trgradg;
                   6587:   int theta;
                   6588: 
                   6589:   double eip, vip;
                   6590: 
                   6591:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6592:   xp=vector(1,npar);
                   6593:   xm=vector(1,npar);
                   6594:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6595:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6596:   
                   6597:   pstamp(ficresstdeij);
                   6598:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6599:   fprintf(ficresstdeij,"# Age");
                   6600:   for(i=1; i<=nlstate;i++){
                   6601:     for(j=1; j<=nlstate;j++)
                   6602:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6603:     fprintf(ficresstdeij," e%1d. ",i);
                   6604:   }
                   6605:   fprintf(ficresstdeij,"\n");
                   6606: 
                   6607:   pstamp(ficrescveij);
                   6608:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6609:   fprintf(ficrescveij,"# Age");
                   6610:   for(i=1; i<=nlstate;i++)
                   6611:     for(j=1; j<=nlstate;j++){
                   6612:       cptj= (j-1)*nlstate+i;
                   6613:       for(i2=1; i2<=nlstate;i2++)
                   6614:        for(j2=1; j2<=nlstate;j2++){
                   6615:          cptj2= (j2-1)*nlstate+i2;
                   6616:          if(cptj2 <= cptj)
                   6617:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6618:        }
                   6619:     }
                   6620:   fprintf(ficrescveij,"\n");
                   6621:   
                   6622:   if(estepm < stepm){
                   6623:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6624:   }
                   6625:   else  hstepm=estepm;   
                   6626:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6627:    * This is mainly to measure the difference between two models: for example
                   6628:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6629:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6630:    * progression in between and thus overestimating or underestimating according
                   6631:    * to the curvature of the survival function. If, for the same date, we 
                   6632:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6633:    * to compare the new estimate of Life expectancy with the same linear 
                   6634:    * hypothesis. A more precise result, taking into account a more precise
                   6635:    * curvature will be obtained if estepm is as small as stepm. */
                   6636: 
                   6637:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6638:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6639:      nhstepm is the number of hstepm from age to agelim 
                   6640:      nstepm is the number of stepm from age to agelin. 
                   6641:      Look at hpijx to understand the reason of that which relies in memory size
                   6642:      and note for a fixed period like estepm months */
                   6643:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6644:      survival function given by stepm (the optimization length). Unfortunately it
                   6645:      means that if the survival funtion is printed only each two years of age and if
                   6646:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6647:      results. So we changed our mind and took the option of the best precision.
                   6648:   */
                   6649:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6650: 
                   6651:   /* If stepm=6 months */
                   6652:   /* nhstepm age range expressed in number of stepm */
                   6653:   agelim=AGESUP;
                   6654:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6655:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6656:   /* if (stepm >= YEARM) hstepm=1;*/
                   6657:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6658:   
                   6659:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6660:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6661:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6662:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6663:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6664:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6665: 
                   6666:   for (age=bage; age<=fage; age ++){ 
                   6667:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6668:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6669:     /* if (stepm >= YEARM) hstepm=1;*/
                   6670:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6671:                
1.126     brouard  6672:     /* If stepm=6 months */
                   6673:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6674:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6675:     
                   6676:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6677:                
1.126     brouard  6678:     /* Computing  Variances of health expectancies */
                   6679:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6680:        decrease memory allocation */
                   6681:     for(theta=1; theta <=npar; theta++){
                   6682:       for(i=1; i<=npar; i++){ 
1.222     brouard  6683:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6684:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6685:       }
1.235     brouard  6686:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6687:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6688:                        
1.126     brouard  6689:       for(j=1; j<= nlstate; j++){
1.222     brouard  6690:        for(i=1; i<=nlstate; i++){
                   6691:          for(h=0; h<=nhstepm-1; h++){
                   6692:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6693:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6694:          }
                   6695:        }
1.126     brouard  6696:       }
1.218     brouard  6697:                        
1.126     brouard  6698:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6699:        for(h=0; h<=nhstepm-1; h++){
                   6700:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6701:        }
1.126     brouard  6702:     }/* End theta */
                   6703:     
                   6704:     
                   6705:     for(h=0; h<=nhstepm-1; h++)
                   6706:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6707:        for(theta=1; theta <=npar; theta++)
                   6708:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6709:     
1.218     brouard  6710:                
1.222     brouard  6711:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6712:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6713:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6714:                
1.222     brouard  6715:     printf("%d|",(int)age);fflush(stdout);
                   6716:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6717:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6718:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6719:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6720:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6721:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6722:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6723:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6724:       }
                   6725:     }
1.320     brouard  6726:     /* if((int)age ==50){ */
                   6727:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6728:     /* } */
1.126     brouard  6729:     /* Computing expectancies */
1.235     brouard  6730:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6731:     for(i=1; i<=nlstate;i++)
                   6732:       for(j=1; j<=nlstate;j++)
1.222     brouard  6733:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6734:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6735:                                        
1.222     brouard  6736:          /* 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  6737:                                        
1.222     brouard  6738:        }
1.269     brouard  6739: 
                   6740:     /* Standard deviation of expectancies ij */                
1.126     brouard  6741:     fprintf(ficresstdeij,"%3.0f",age );
                   6742:     for(i=1; i<=nlstate;i++){
                   6743:       eip=0.;
                   6744:       vip=0.;
                   6745:       for(j=1; j<=nlstate;j++){
1.222     brouard  6746:        eip += eij[i][j][(int)age];
                   6747:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6748:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6749:        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  6750:       }
                   6751:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6752:     }
                   6753:     fprintf(ficresstdeij,"\n");
1.218     brouard  6754:                
1.269     brouard  6755:     /* Variance of expectancies ij */          
1.126     brouard  6756:     fprintf(ficrescveij,"%3.0f",age );
                   6757:     for(i=1; i<=nlstate;i++)
                   6758:       for(j=1; j<=nlstate;j++){
1.222     brouard  6759:        cptj= (j-1)*nlstate+i;
                   6760:        for(i2=1; i2<=nlstate;i2++)
                   6761:          for(j2=1; j2<=nlstate;j2++){
                   6762:            cptj2= (j2-1)*nlstate+i2;
                   6763:            if(cptj2 <= cptj)
                   6764:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6765:          }
1.126     brouard  6766:       }
                   6767:     fprintf(ficrescveij,"\n");
1.218     brouard  6768:                
1.126     brouard  6769:   }
                   6770:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6771:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6772:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6773:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6774:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6775:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6776:   printf("\n");
                   6777:   fprintf(ficlog,"\n");
1.218     brouard  6778:        
1.126     brouard  6779:   free_vector(xm,1,npar);
                   6780:   free_vector(xp,1,npar);
                   6781:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6782:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6783:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6784: }
1.218     brouard  6785:  
1.126     brouard  6786: /************ Variance ******************/
1.235     brouard  6787:  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  6788:  {
1.279     brouard  6789:    /** Variance of health expectancies 
                   6790:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6791:     * double **newm;
                   6792:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6793:     */
1.218     brouard  6794:   
                   6795:    /* int movingaverage(); */
                   6796:    double **dnewm,**doldm;
                   6797:    double **dnewmp,**doldmp;
                   6798:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6799:    int first=0;
1.218     brouard  6800:    int k;
                   6801:    double *xp;
1.279     brouard  6802:    double **gp, **gm;  /**< for var eij */
                   6803:    double ***gradg, ***trgradg; /**< for var eij */
                   6804:    double **gradgp, **trgradgp; /**< for var p point j */
                   6805:    double *gpp, *gmp; /**< for var p point j */
                   6806:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6807:    double ***p3mat;
                   6808:    double age,agelim, hf;
                   6809:    /* double ***mobaverage; */
                   6810:    int theta;
                   6811:    char digit[4];
                   6812:    char digitp[25];
                   6813: 
                   6814:    char fileresprobmorprev[FILENAMELENGTH];
                   6815: 
                   6816:    if(popbased==1){
                   6817:      if(mobilav!=0)
                   6818:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6819:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6820:    }
                   6821:    else 
                   6822:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6823: 
1.218     brouard  6824:    /* if (mobilav!=0) { */
                   6825:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6826:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6827:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6828:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6829:    /*   } */
                   6830:    /* } */
                   6831: 
                   6832:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6833:    sprintf(digit,"%-d",ij);
                   6834:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6835:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6836:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6837:    strcat(fileresprobmorprev,fileresu);
                   6838:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6839:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6840:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6841:    }
                   6842:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6843:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6844:    pstamp(ficresprobmorprev);
                   6845:    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  6846:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6847: 
                   6848:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6849:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6850:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6851:    /* } */
                   6852:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  6853:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  6854:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6855:    }
1.337     brouard  6856:    /* for(j=1;j<=cptcoveff;j++)  */
                   6857:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6858:    fprintf(ficresprobmorprev,"\n");
                   6859: 
1.218     brouard  6860:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6861:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6862:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6863:      for(i=1; i<=nlstate;i++)
                   6864:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6865:    }  
                   6866:    fprintf(ficresprobmorprev,"\n");
                   6867:   
                   6868:    fprintf(ficgp,"\n# Routine varevsij");
                   6869:    fprintf(ficgp,"\nunset title \n");
                   6870:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6871:    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");
                   6872:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6873: 
1.218     brouard  6874:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6875:    pstamp(ficresvij);
                   6876:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6877:    if(popbased==1)
                   6878:      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);
                   6879:    else
                   6880:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6881:    fprintf(ficresvij,"# Age");
                   6882:    for(i=1; i<=nlstate;i++)
                   6883:      for(j=1; j<=nlstate;j++)
                   6884:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6885:    fprintf(ficresvij,"\n");
                   6886: 
                   6887:    xp=vector(1,npar);
                   6888:    dnewm=matrix(1,nlstate,1,npar);
                   6889:    doldm=matrix(1,nlstate,1,nlstate);
                   6890:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6891:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6892: 
                   6893:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6894:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6895:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6896:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6897:   
1.218     brouard  6898:    if(estepm < stepm){
                   6899:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6900:    }
                   6901:    else  hstepm=estepm;   
                   6902:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6903:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6904:       nhstepm is the number of hstepm from age to agelim 
                   6905:       nstepm is the number of stepm from age to agelim. 
                   6906:       Look at function hpijx to understand why because of memory size limitations, 
                   6907:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6908:       survival function given by stepm (the optimization length). Unfortunately it
                   6909:       means that if the survival funtion is printed every two years of age and if
                   6910:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6911:       results. So we changed our mind and took the option of the best precision.
                   6912:    */
                   6913:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6914:    agelim = AGESUP;
                   6915:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6916:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6917:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6918:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6919:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6920:      gp=matrix(0,nhstepm,1,nlstate);
                   6921:      gm=matrix(0,nhstepm,1,nlstate);
                   6922:                
                   6923:                
                   6924:      for(theta=1; theta <=npar; theta++){
                   6925:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6926:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6927:        }
1.279     brouard  6928:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6929:        * returns into prlim .
1.288     brouard  6930:        */
1.242     brouard  6931:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6932: 
                   6933:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6934:        if (popbased==1) {
                   6935:         if(mobilav ==0){
                   6936:           for(i=1; i<=nlstate;i++)
                   6937:             prlim[i][i]=probs[(int)age][i][ij];
                   6938:         }else{ /* mobilav */ 
                   6939:           for(i=1; i<=nlstate;i++)
                   6940:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6941:         }
                   6942:        }
1.295     brouard  6943:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6944:        */                      
                   6945:        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  6946:        /**< 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  6947:        * at horizon h in state j including mortality.
                   6948:        */
1.218     brouard  6949:        for(j=1; j<= nlstate; j++){
                   6950:         for(h=0; h<=nhstepm; h++){
                   6951:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6952:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6953:         }
                   6954:        }
1.279     brouard  6955:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6956:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6957:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6958:        */
                   6959:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6960:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6961:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6962:        }
                   6963:        
                   6964:        /* Again with minus shift */
1.218     brouard  6965:                        
                   6966:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6967:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6968: 
1.242     brouard  6969:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6970:                        
                   6971:        if (popbased==1) {
                   6972:         if(mobilav ==0){
                   6973:           for(i=1; i<=nlstate;i++)
                   6974:             prlim[i][i]=probs[(int)age][i][ij];
                   6975:         }else{ /* mobilav */ 
                   6976:           for(i=1; i<=nlstate;i++)
                   6977:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6978:         }
                   6979:        }
                   6980:                        
1.235     brouard  6981:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6982:                        
                   6983:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6984:         for(h=0; h<=nhstepm; h++){
                   6985:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6986:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6987:         }
                   6988:        }
                   6989:        /* This for computing probability of death (h=1 means
                   6990:          computed over hstepm matrices product = hstepm*stepm months) 
                   6991:          as a weighted average of prlim.
                   6992:        */
                   6993:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6994:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6995:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6996:        }    
1.279     brouard  6997:        /* end shifting computations */
                   6998: 
                   6999:        /**< Computing gradient matrix at horizon h 
                   7000:        */
1.218     brouard  7001:        for(j=1; j<= nlstate; j++) /* vareij */
                   7002:         for(h=0; h<=nhstepm; h++){
                   7003:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7004:         }
1.279     brouard  7005:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7006:        */
                   7007:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7008:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7009:        }
                   7010:                        
                   7011:      } /* End theta */
1.279     brouard  7012:      
                   7013:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7014:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7015:                
                   7016:      for(h=0; h<=nhstepm; h++) /* veij */
                   7017:        for(j=1; j<=nlstate;j++)
                   7018:         for(theta=1; theta <=npar; theta++)
                   7019:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7020:                
                   7021:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7022:        for(theta=1; theta <=npar; theta++)
                   7023:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7024:      /**< as well as its transposed matrix 
                   7025:       */               
1.218     brouard  7026:                
                   7027:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7028:      for(i=1;i<=nlstate;i++)
                   7029:        for(j=1;j<=nlstate;j++)
                   7030:         vareij[i][j][(int)age] =0.;
1.279     brouard  7031: 
                   7032:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7033:       * and k (nhstepm) formula 15 of article
                   7034:       * Lievre-Brouard-Heathcote
                   7035:       */
                   7036:      
1.218     brouard  7037:      for(h=0;h<=nhstepm;h++){
                   7038:        for(k=0;k<=nhstepm;k++){
                   7039:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7040:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7041:         for(i=1;i<=nlstate;i++)
                   7042:           for(j=1;j<=nlstate;j++)
                   7043:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7044:        }
                   7045:      }
                   7046:                
1.279     brouard  7047:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7048:       * p.j overall mortality formula 49 but computed directly because
                   7049:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7050:       * wix is independent of theta.
                   7051:       */
1.218     brouard  7052:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7053:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7054:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7055:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7056:         varppt[j][i]=doldmp[j][i];
                   7057:      /* end ppptj */
                   7058:      /*  x centered again */
                   7059:                
1.242     brouard  7060:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7061:                
                   7062:      if (popbased==1) {
                   7063:        if(mobilav ==0){
                   7064:         for(i=1; i<=nlstate;i++)
                   7065:           prlim[i][i]=probs[(int)age][i][ij];
                   7066:        }else{ /* mobilav */ 
                   7067:         for(i=1; i<=nlstate;i++)
                   7068:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7069:        }
                   7070:      }
                   7071:                
                   7072:      /* This for computing probability of death (h=1 means
                   7073:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7074:        as a weighted average of prlim.
                   7075:      */
1.235     brouard  7076:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7077:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7078:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7079:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7080:      }    
                   7081:      /* end probability of death */
                   7082:                
                   7083:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7084:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7085:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7086:        for(i=1; i<=nlstate;i++){
                   7087:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7088:        }
                   7089:      } 
                   7090:      fprintf(ficresprobmorprev,"\n");
                   7091:                
                   7092:      fprintf(ficresvij,"%.0f ",age );
                   7093:      for(i=1; i<=nlstate;i++)
                   7094:        for(j=1; j<=nlstate;j++){
                   7095:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7096:        }
                   7097:      fprintf(ficresvij,"\n");
                   7098:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7099:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7100:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7101:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7102:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7103:    } /* End age */
                   7104:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7105:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7106:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7107:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7108:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7109:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7110:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7111:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7112:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7113:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7114:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7115:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7116:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7117:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7118:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7119:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7120:    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);
                   7121:    /*  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  7122:     */
1.218     brouard  7123:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7124:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7125: 
1.218     brouard  7126:    free_vector(xp,1,npar);
                   7127:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7128:    free_matrix(dnewm,1,nlstate,1,npar);
                   7129:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7130:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7131:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7132:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7133:    fclose(ficresprobmorprev);
                   7134:    fflush(ficgp);
                   7135:    fflush(fichtm); 
                   7136:  }  /* end varevsij */
1.126     brouard  7137: 
                   7138: /************ Variance of prevlim ******************/
1.269     brouard  7139:  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  7140: {
1.205     brouard  7141:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7142:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7143: 
1.268     brouard  7144:   double **dnewmpar,**doldm;
1.126     brouard  7145:   int i, j, nhstepm, hstepm;
                   7146:   double *xp;
                   7147:   double *gp, *gm;
                   7148:   double **gradg, **trgradg;
1.208     brouard  7149:   double **mgm, **mgp;
1.126     brouard  7150:   double age,agelim;
                   7151:   int theta;
                   7152:   
                   7153:   pstamp(ficresvpl);
1.288     brouard  7154:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7155:   fprintf(ficresvpl,"# Age ");
                   7156:   if(nresult >=1)
                   7157:     fprintf(ficresvpl," Result# ");
1.126     brouard  7158:   for(i=1; i<=nlstate;i++)
                   7159:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7160:   fprintf(ficresvpl,"\n");
                   7161: 
                   7162:   xp=vector(1,npar);
1.268     brouard  7163:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7164:   doldm=matrix(1,nlstate,1,nlstate);
                   7165:   
                   7166:   hstepm=1*YEARM; /* Every year of age */
                   7167:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7168:   agelim = AGESUP;
                   7169:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7170:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7171:     if (stepm >= YEARM) hstepm=1;
                   7172:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7173:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7174:     mgp=matrix(1,npar,1,nlstate);
                   7175:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7176:     gp=vector(1,nlstate);
                   7177:     gm=vector(1,nlstate);
                   7178: 
                   7179:     for(theta=1; theta <=npar; theta++){
                   7180:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7181:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7182:       }
1.288     brouard  7183:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7184:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7185:       /* else */
                   7186:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7187:       for(i=1;i<=nlstate;i++){
1.126     brouard  7188:        gp[i] = prlim[i][i];
1.208     brouard  7189:        mgp[theta][i] = prlim[i][i];
                   7190:       }
1.126     brouard  7191:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7192:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7193:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7194:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7195:       /* else */
                   7196:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7197:       for(i=1;i<=nlstate;i++){
1.126     brouard  7198:        gm[i] = prlim[i][i];
1.208     brouard  7199:        mgm[theta][i] = prlim[i][i];
                   7200:       }
1.126     brouard  7201:       for(i=1;i<=nlstate;i++)
                   7202:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7203:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7204:     } /* End theta */
                   7205: 
                   7206:     trgradg =matrix(1,nlstate,1,npar);
                   7207: 
                   7208:     for(j=1; j<=nlstate;j++)
                   7209:       for(theta=1; theta <=npar; theta++)
                   7210:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7211:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7212:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7213:     /*   for(j=1; j<=nlstate;j++){ */
                   7214:     /*         printf(" %d ",j); */
                   7215:     /*         for(theta=1; theta <=npar; theta++) */
                   7216:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7217:     /*         printf("\n "); */
                   7218:     /*   } */
                   7219:     /* } */
                   7220:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7221:     /*   printf("\n gradg %d ",(int)age); */
                   7222:     /*   for(j=1; j<=nlstate;j++){ */
                   7223:     /*         printf("%d ",j); */
                   7224:     /*         for(theta=1; theta <=npar; theta++) */
                   7225:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7226:     /*         printf("\n "); */
                   7227:     /*   } */
                   7228:     /* } */
1.126     brouard  7229: 
                   7230:     for(i=1;i<=nlstate;i++)
                   7231:       varpl[i][(int)age] =0.;
1.209     brouard  7232:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7233:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7234:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7235:     }else{
1.268     brouard  7236:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7237:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7238:     }
1.126     brouard  7239:     for(i=1;i<=nlstate;i++)
                   7240:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7241: 
                   7242:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7243:     if(nresult >=1)
                   7244:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7245:     for(i=1; i<=nlstate;i++){
1.126     brouard  7246:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7247:       /* for(j=1;j<=nlstate;j++) */
                   7248:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7249:     }
1.126     brouard  7250:     fprintf(ficresvpl,"\n");
                   7251:     free_vector(gp,1,nlstate);
                   7252:     free_vector(gm,1,nlstate);
1.208     brouard  7253:     free_matrix(mgm,1,npar,1,nlstate);
                   7254:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7255:     free_matrix(gradg,1,npar,1,nlstate);
                   7256:     free_matrix(trgradg,1,nlstate,1,npar);
                   7257:   } /* End age */
                   7258: 
                   7259:   free_vector(xp,1,npar);
                   7260:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7261:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7262: 
                   7263: }
                   7264: 
                   7265: 
                   7266: /************ Variance of backprevalence limit ******************/
1.269     brouard  7267:  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  7268: {
                   7269:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7270:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7271: 
                   7272:   double **dnewmpar,**doldm;
                   7273:   int i, j, nhstepm, hstepm;
                   7274:   double *xp;
                   7275:   double *gp, *gm;
                   7276:   double **gradg, **trgradg;
                   7277:   double **mgm, **mgp;
                   7278:   double age,agelim;
                   7279:   int theta;
                   7280:   
                   7281:   pstamp(ficresvbl);
                   7282:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7283:   fprintf(ficresvbl,"# Age ");
                   7284:   if(nresult >=1)
                   7285:     fprintf(ficresvbl," Result# ");
                   7286:   for(i=1; i<=nlstate;i++)
                   7287:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7288:   fprintf(ficresvbl,"\n");
                   7289: 
                   7290:   xp=vector(1,npar);
                   7291:   dnewmpar=matrix(1,nlstate,1,npar);
                   7292:   doldm=matrix(1,nlstate,1,nlstate);
                   7293:   
                   7294:   hstepm=1*YEARM; /* Every year of age */
                   7295:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7296:   agelim = AGEINF;
                   7297:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7298:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7299:     if (stepm >= YEARM) hstepm=1;
                   7300:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7301:     gradg=matrix(1,npar,1,nlstate);
                   7302:     mgp=matrix(1,npar,1,nlstate);
                   7303:     mgm=matrix(1,npar,1,nlstate);
                   7304:     gp=vector(1,nlstate);
                   7305:     gm=vector(1,nlstate);
                   7306: 
                   7307:     for(theta=1; theta <=npar; theta++){
                   7308:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7309:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7310:       }
                   7311:       if(mobilavproj > 0 )
                   7312:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7313:       else
                   7314:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7315:       for(i=1;i<=nlstate;i++){
                   7316:        gp[i] = bprlim[i][i];
                   7317:        mgp[theta][i] = bprlim[i][i];
                   7318:       }
                   7319:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7320:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7321:        if(mobilavproj > 0 )
                   7322:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7323:        else
                   7324:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7325:       for(i=1;i<=nlstate;i++){
                   7326:        gm[i] = bprlim[i][i];
                   7327:        mgm[theta][i] = bprlim[i][i];
                   7328:       }
                   7329:       for(i=1;i<=nlstate;i++)
                   7330:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7331:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7332:     } /* End theta */
                   7333: 
                   7334:     trgradg =matrix(1,nlstate,1,npar);
                   7335: 
                   7336:     for(j=1; j<=nlstate;j++)
                   7337:       for(theta=1; theta <=npar; theta++)
                   7338:        trgradg[j][theta]=gradg[theta][j];
                   7339:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7340:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7341:     /*   for(j=1; j<=nlstate;j++){ */
                   7342:     /*         printf(" %d ",j); */
                   7343:     /*         for(theta=1; theta <=npar; theta++) */
                   7344:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7345:     /*         printf("\n "); */
                   7346:     /*   } */
                   7347:     /* } */
                   7348:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7349:     /*   printf("\n gradg %d ",(int)age); */
                   7350:     /*   for(j=1; j<=nlstate;j++){ */
                   7351:     /*         printf("%d ",j); */
                   7352:     /*         for(theta=1; theta <=npar; theta++) */
                   7353:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7354:     /*         printf("\n "); */
                   7355:     /*   } */
                   7356:     /* } */
                   7357: 
                   7358:     for(i=1;i<=nlstate;i++)
                   7359:       varbpl[i][(int)age] =0.;
                   7360:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7361:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7362:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7363:     }else{
                   7364:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7365:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7366:     }
                   7367:     for(i=1;i<=nlstate;i++)
                   7368:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7369: 
                   7370:     fprintf(ficresvbl,"%.0f ",age );
                   7371:     if(nresult >=1)
                   7372:       fprintf(ficresvbl,"%d ",nres );
                   7373:     for(i=1; i<=nlstate;i++)
                   7374:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7375:     fprintf(ficresvbl,"\n");
                   7376:     free_vector(gp,1,nlstate);
                   7377:     free_vector(gm,1,nlstate);
                   7378:     free_matrix(mgm,1,npar,1,nlstate);
                   7379:     free_matrix(mgp,1,npar,1,nlstate);
                   7380:     free_matrix(gradg,1,npar,1,nlstate);
                   7381:     free_matrix(trgradg,1,nlstate,1,npar);
                   7382:   } /* End age */
                   7383: 
                   7384:   free_vector(xp,1,npar);
                   7385:   free_matrix(doldm,1,nlstate,1,npar);
                   7386:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7387: 
                   7388: }
                   7389: 
                   7390: /************ Variance of one-step probabilities  ******************/
                   7391: 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  7392:  {
                   7393:    int i, j=0,  k1, l1, tj;
                   7394:    int k2, l2, j1,  z1;
                   7395:    int k=0, l;
                   7396:    int first=1, first1, first2;
1.326     brouard  7397:    int nres=0; /* New */
1.222     brouard  7398:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7399:    double **dnewm,**doldm;
                   7400:    double *xp;
                   7401:    double *gp, *gm;
                   7402:    double **gradg, **trgradg;
                   7403:    double **mu;
                   7404:    double age, cov[NCOVMAX+1];
                   7405:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7406:    int theta;
                   7407:    char fileresprob[FILENAMELENGTH];
                   7408:    char fileresprobcov[FILENAMELENGTH];
                   7409:    char fileresprobcor[FILENAMELENGTH];
                   7410:    double ***varpij;
                   7411: 
                   7412:    strcpy(fileresprob,"PROB_"); 
                   7413:    strcat(fileresprob,fileres);
                   7414:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7415:      printf("Problem with resultfile: %s\n", fileresprob);
                   7416:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7417:    }
                   7418:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7419:    strcat(fileresprobcov,fileresu);
                   7420:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7421:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7422:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7423:    }
                   7424:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7425:    strcat(fileresprobcor,fileresu);
                   7426:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7427:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7428:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7429:    }
                   7430:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7431:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7432:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7433:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7434:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7435:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7436:    pstamp(ficresprob);
                   7437:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7438:    fprintf(ficresprob,"# Age");
                   7439:    pstamp(ficresprobcov);
                   7440:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7441:    fprintf(ficresprobcov,"# Age");
                   7442:    pstamp(ficresprobcor);
                   7443:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7444:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7445: 
                   7446: 
1.222     brouard  7447:    for(i=1; i<=nlstate;i++)
                   7448:      for(j=1; j<=(nlstate+ndeath);j++){
                   7449:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7450:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7451:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7452:      }  
                   7453:    /* fprintf(ficresprob,"\n");
                   7454:       fprintf(ficresprobcov,"\n");
                   7455:       fprintf(ficresprobcor,"\n");
                   7456:    */
                   7457:    xp=vector(1,npar);
                   7458:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7459:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7460:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7461:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7462:    first=1;
                   7463:    fprintf(ficgp,"\n# Routine varprob");
                   7464:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7465:    fprintf(fichtm,"\n");
                   7466: 
1.288     brouard  7467:    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  7468:    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);
                   7469:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7470: and drawn. It helps understanding how is the covariance between two incidences.\
                   7471:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7472:    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  7473: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7474: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7475: standard deviations wide on each axis. <br>\
                   7476:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7477:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7478: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7479: 
1.222     brouard  7480:    cov[1]=1;
                   7481:    /* tj=cptcoveff; */
1.225     brouard  7482:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7483:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7484:    j1=0;
1.332     brouard  7485: 
                   7486:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7487:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7488:      /* 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  7489:      if(tj != 1 && TKresult[nres]!= j1)
                   7490:        continue;
                   7491: 
                   7492:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7493:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7494:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7495:      if  (cptcovn>0) {
1.334     brouard  7496:        fprintf(ficresprob, "\n#********** Variable ");
                   7497:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7498:        fprintf(ficgp, "\n#********** Variable ");
                   7499:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7500:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7501: 
                   7502:        /* Including quantitative variables of the resultline to be done */
                   7503:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7504:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7505:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7506:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
1.334     brouard  7507:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7508:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7509:             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  */
                   7510:             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  */
                   7511:             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  */
                   7512:             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  */
                   7513:             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  */
                   7514:             fprintf(ficresprob,"fixed ");
                   7515:             fprintf(ficresprobcov,"fixed ");
                   7516:             fprintf(ficgp,"fixed ");
                   7517:             fprintf(fichtmcov,"fixed ");
                   7518:             fprintf(ficresprobcor,"fixed ");
                   7519:           }else{
                   7520:             fprintf(ficresprob,"varyi ");
                   7521:             fprintf(ficresprobcov,"varyi ");
                   7522:             fprintf(ficgp,"varyi ");
                   7523:             fprintf(fichtmcov,"varyi ");
                   7524:             fprintf(ficresprobcor,"varyi ");
                   7525:           }
                   7526:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7527:           /* For each selected (single) quantitative value */
1.337     brouard  7528:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7529:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7530:             fprintf(ficresprob,"fixed ");
                   7531:             fprintf(ficresprobcov,"fixed ");
                   7532:             fprintf(ficgp,"fixed ");
                   7533:             fprintf(fichtmcov,"fixed ");
                   7534:             fprintf(ficresprobcor,"fixed ");
                   7535:           }else{
                   7536:             fprintf(ficresprob,"varyi ");
                   7537:             fprintf(ficresprobcov,"varyi ");
                   7538:             fprintf(ficgp,"varyi ");
                   7539:             fprintf(fichtmcov,"varyi ");
                   7540:             fprintf(ficresprobcor,"varyi ");
                   7541:           }
                   7542:         }else{
                   7543:           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 */
                   7544:           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 */
                   7545:           exit(1);
                   7546:         }
                   7547:        } /* End loop on variable of this resultline */
                   7548:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7549:        fprintf(ficresprob, "**********\n#\n");
                   7550:        fprintf(ficresprobcov, "**********\n#\n");
                   7551:        fprintf(ficgp, "**********\n#\n");
                   7552:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7553:        fprintf(ficresprobcor, "**********\n#");    
                   7554:        if(invalidvarcomb[j1]){
                   7555:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7556:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7557:         continue;
                   7558:        }
                   7559:      }
                   7560:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7561:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7562:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7563:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7564:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7565:        cov[2]=age;
                   7566:        if(nagesqr==1)
                   7567:         cov[3]= age*age;
1.334     brouard  7568:        /* New code end of combination but for each resultline */
                   7569:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7570:         if(Typevar[k1]==1){ /* A product with age */
                   7571:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7572:         }else{
1.334     brouard  7573:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7574:         }
1.334     brouard  7575:        }/* End of loop on model equation */
                   7576: /* Old code */
                   7577:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7578:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7579:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7580:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7581:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7582:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7583:        /*                                                                  * 1  1 1 1 1 */
                   7584:        /*                                                                  * 2  2 1 1 1 */
                   7585:        /*                                                                  * 3  1 2 1 1 */
                   7586:        /*                                                                  *\/ */
                   7587:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7588:        /* } */
                   7589:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7590:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7591:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7592:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7593:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7594:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7595:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7596:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7597:        /*         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]); */
                   7598:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7599:        /*         /\* exit(1); *\/ */
                   7600:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7601:        /*       } */
                   7602:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7603:        /* } */
                   7604:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7605:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7606:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7607:        /*           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]])]; */
                   7608:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7609:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7610:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7611:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7612:        /*         } */
                   7613:        /*       }else{ */
                   7614:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7615:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7616:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7617:        /*         }else{ */
                   7618:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7619:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7620:        /*         } */
                   7621:        /*       } */
                   7622:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7623:        /* } */                 
1.326     brouard  7624: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7625:        for(theta=1; theta <=npar; theta++){
                   7626:         for(i=1; i<=npar; i++)
                   7627:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7628:                                
1.222     brouard  7629:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7630:                                
1.222     brouard  7631:         k=0;
                   7632:         for(i=1; i<= (nlstate); i++){
                   7633:           for(j=1; j<=(nlstate+ndeath);j++){
                   7634:             k=k+1;
                   7635:             gp[k]=pmmij[i][j];
                   7636:           }
                   7637:         }
1.220     brouard  7638:                                
1.222     brouard  7639:         for(i=1; i<=npar; i++)
                   7640:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7641:                                
1.222     brouard  7642:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7643:         k=0;
                   7644:         for(i=1; i<=(nlstate); i++){
                   7645:           for(j=1; j<=(nlstate+ndeath);j++){
                   7646:             k=k+1;
                   7647:             gm[k]=pmmij[i][j];
                   7648:           }
                   7649:         }
1.220     brouard  7650:                                
1.222     brouard  7651:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7652:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7653:        }
1.126     brouard  7654: 
1.222     brouard  7655:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7656:         for(theta=1; theta <=npar; theta++)
                   7657:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7658:                        
1.222     brouard  7659:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7660:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7661:                        
1.222     brouard  7662:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7663:                        
1.222     brouard  7664:        k=0;
                   7665:        for(i=1; i<=(nlstate); i++){
                   7666:         for(j=1; j<=(nlstate+ndeath);j++){
                   7667:           k=k+1;
                   7668:           mu[k][(int) age]=pmmij[i][j];
                   7669:         }
                   7670:        }
                   7671:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7672:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7673:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7674:                        
1.222     brouard  7675:        /*printf("\n%d ",(int)age);
                   7676:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7677:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7678:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7679:         }*/
1.220     brouard  7680:                        
1.222     brouard  7681:        fprintf(ficresprob,"\n%d ",(int)age);
                   7682:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7683:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7684:                        
1.222     brouard  7685:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7686:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7687:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7688:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7689:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7690:        }
                   7691:        i=0;
                   7692:        for (k=1; k<=(nlstate);k++){
                   7693:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7694:           i++;
                   7695:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7696:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7697:           for (j=1; j<=i;j++){
                   7698:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7699:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7700:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7701:           }
                   7702:         }
                   7703:        }/* end of loop for state */
                   7704:      } /* end of loop for age */
                   7705:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7706:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7707:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7708:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7709:     
                   7710:      /* Confidence intervalle of pij  */
                   7711:      /*
                   7712:        fprintf(ficgp,"\nunset parametric;unset label");
                   7713:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7714:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7715:        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);
                   7716:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7717:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7718:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7719:      */
                   7720:                
                   7721:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7722:      first1=1;first2=2;
                   7723:      for (k2=1; k2<=(nlstate);k2++){
                   7724:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7725:         if(l2==k2) continue;
                   7726:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7727:         for (k1=1; k1<=(nlstate);k1++){
                   7728:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7729:             if(l1==k1) continue;
                   7730:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7731:             if(i<=j) continue;
                   7732:             for (age=bage; age<=fage; age ++){ 
                   7733:               if ((int)age %5==0){
                   7734:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7735:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7736:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7737:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7738:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7739:                 c12=cv12/sqrt(v1*v2);
                   7740:                 /* Computing eigen value of matrix of covariance */
                   7741:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7742:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7743:                 if ((lc2 <0) || (lc1 <0) ){
                   7744:                   if(first2==1){
                   7745:                     first1=0;
                   7746:                     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);
                   7747:                   }
                   7748:                   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);
                   7749:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7750:                   /* lc2=fabs(lc2); */
                   7751:                 }
1.220     brouard  7752:                                                                
1.222     brouard  7753:                 /* Eigen vectors */
1.280     brouard  7754:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7755:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7756:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7757:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7758:                 }else
                   7759:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7760:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7761:                 v21=(lc1-v1)/cv12*v11;
                   7762:                 v12=-v21;
                   7763:                 v22=v11;
                   7764:                 tnalp=v21/v11;
                   7765:                 if(first1==1){
                   7766:                   first1=0;
                   7767:                   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);
                   7768:                 }
                   7769:                 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);
                   7770:                 /*printf(fignu*/
                   7771:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7772:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7773:                 if(first==1){
                   7774:                   first=0;
                   7775:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7776:                   fprintf(ficgp,"\nset parametric;unset label");
                   7777:                   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);
                   7778:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7779:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7780:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7781: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7782:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7783:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7784:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7785:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7786:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7787:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7788:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7789:                   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  7790:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7791:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7792:                 }else{
                   7793:                   first=0;
                   7794:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7795:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7796:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7797:                   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  7798:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7799:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7800:                 }/* if first */
                   7801:               } /* age mod 5 */
                   7802:             } /* end loop age */
                   7803:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7804:             first=1;
                   7805:           } /*l12 */
                   7806:         } /* k12 */
                   7807:        } /*l1 */
                   7808:      }/* k1 */
1.332     brouard  7809:    }  /* loop on combination of covariates j1 */
1.326     brouard  7810:    } /* loop on nres */
1.222     brouard  7811:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7812:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7813:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7814:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7815:    free_vector(xp,1,npar);
                   7816:    fclose(ficresprob);
                   7817:    fclose(ficresprobcov);
                   7818:    fclose(ficresprobcor);
                   7819:    fflush(ficgp);
                   7820:    fflush(fichtmcov);
                   7821:  }
1.126     brouard  7822: 
                   7823: 
                   7824: /******************* Printing html file ***********/
1.201     brouard  7825: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7826:                  int lastpass, int stepm, int weightopt, char model[],\
                   7827:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7828:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7829:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7830:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7831:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7832:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7833:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7834:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7835: </ul>");
1.319     brouard  7836: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7837: /* </ul>", model); */
1.214     brouard  7838:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7839:    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",
                   7840:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7841:    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  7842:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7843:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7844:    fprintf(fichtm,"\
                   7845:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7846:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7847:    fprintf(fichtm,"\
1.217     brouard  7848:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7849:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7850:    fprintf(fichtm,"\
1.288     brouard  7851:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7852:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7853:    fprintf(fichtm,"\
1.288     brouard  7854:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7855:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7856:    fprintf(fichtm,"\
1.211     brouard  7857:  - (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  7858:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7859:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7860:    if(prevfcast==1){
                   7861:      fprintf(fichtm,"\
                   7862:  - Prevalence projections by age and states:                           \
1.201     brouard  7863:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7864:    }
1.126     brouard  7865: 
                   7866: 
1.225     brouard  7867:    m=pow(2,cptcoveff);
1.222     brouard  7868:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7869: 
1.317     brouard  7870:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7871: 
                   7872:    jj1=0;
                   7873: 
                   7874:    fprintf(fichtm," \n<ul>");
1.337     brouard  7875:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7876:      /* k1=nres; */
1.338     brouard  7877:      k1=TKresult[nres];
                   7878:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7879:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7880:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7881:    /*     continue; */
1.264     brouard  7882:      jj1++;
                   7883:      if (cptcovn > 0) {
                   7884:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7885:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7886:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7887:        }
1.337     brouard  7888:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7889:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7890:        /* } */
                   7891:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7892:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7893:        /* } */
1.264     brouard  7894:        fprintf(fichtm,"\">");
                   7895:        
                   7896:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7897:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7898:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7899:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7900:        }
1.337     brouard  7901:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7902:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7903:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7904:        /* } */
                   7905:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7906:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7907:        /* } */
1.264     brouard  7908:        if(invalidvarcomb[k1]){
                   7909:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7910:         continue;
                   7911:        }
                   7912:        fprintf(fichtm,"</a></li>");
                   7913:      } /* cptcovn >0 */
                   7914:    }
1.317     brouard  7915:    fprintf(fichtm," \n</ul>");
1.264     brouard  7916: 
1.222     brouard  7917:    jj1=0;
1.237     brouard  7918: 
1.337     brouard  7919:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7920:      /* k1=nres; */
1.338     brouard  7921:      k1=TKresult[nres];
                   7922:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7923:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7924:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7925:    /*     continue; */
1.220     brouard  7926: 
1.222     brouard  7927:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7928:      jj1++;
                   7929:      if (cptcovn > 0) {
1.264     brouard  7930:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7931:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7932:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7933:        }
1.337     brouard  7934:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7935:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7936:        /* } */
1.264     brouard  7937:        fprintf(fichtm,"\"</a>");
                   7938:  
1.222     brouard  7939:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7940:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7941:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7942:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7943:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7944:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7945:        }
1.230     brouard  7946:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7947:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7948:        if(invalidvarcomb[k1]){
                   7949:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7950:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7951:         continue;
                   7952:        }
                   7953:      }
                   7954:      /* aij, bij */
1.259     brouard  7955:      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  7956: <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  7957:      /* Pij */
1.241     brouard  7958:      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> \
                   7959: <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  7960:      /* Quasi-incidences */
                   7961:      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  7962:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7963:  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  7964: 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> \
                   7965: <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  7966:      /* Survival functions (period) in state j */
                   7967:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7968:        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);
                   7969:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7970:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7971:      }
                   7972:      /* State specific survival functions (period) */
                   7973:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7974:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7975:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7976:  <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);
                   7977:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7978:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7979:      }
1.288     brouard  7980:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7981:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7982:        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);
1.338     brouard  7983:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7984:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7985:      }
1.296     brouard  7986:      if(prevbcast==1){
1.288     brouard  7987:        /* Backward prevalence in each health state */
1.222     brouard  7988:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7989:         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>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   7990:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7991:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7992:        }
1.217     brouard  7993:      }
1.222     brouard  7994:      if(prevfcast==1){
1.288     brouard  7995:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7996:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7997:         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);
                   7998:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7999:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8000:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8001:        }
                   8002:      }
1.296     brouard  8003:      if(prevbcast==1){
1.268     brouard  8004:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8005:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8006:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8007:  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 \
                   8008:  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  8009: 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);
                   8010:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8011:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8012:        }
                   8013:      }
1.220     brouard  8014:         
1.222     brouard  8015:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8016:        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);
                   8017:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8018:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8019:      }
                   8020:      /* } /\* end i1 *\/ */
1.337     brouard  8021:    }/* End k1=nres */
1.222     brouard  8022:    fprintf(fichtm,"</ul>");
1.126     brouard  8023: 
1.222     brouard  8024:    fprintf(fichtm,"\
1.126     brouard  8025: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8026:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8027:  - 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  8028: But because parameters are usually highly correlated (a higher incidence of disability \
                   8029: and a higher incidence of recovery can give very close observed transition) it might \
                   8030: be very useful to look not only at linear confidence intervals estimated from the \
                   8031: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8032: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8033: covariance matrix of the one-step probabilities. \
                   8034: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8035: 
1.222     brouard  8036:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8037:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8038:    fprintf(fichtm,"\
1.126     brouard  8039:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8040:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8041: 
1.222     brouard  8042:    fprintf(fichtm,"\
1.126     brouard  8043:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8044:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8045:    fprintf(fichtm,"\
1.126     brouard  8046:  - 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): \
                   8047:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8048:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8049:    fprintf(fichtm,"\
1.126     brouard  8050:  - (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): \
                   8051:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8052:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8053:    fprintf(fichtm,"\
1.288     brouard  8054:  - 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  8055:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8056:    fprintf(fichtm,"\
1.128     brouard  8057:  - 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  8058:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8059:    fprintf(fichtm,"\
1.288     brouard  8060:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8061:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8062: 
                   8063: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8064: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8065: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8066: /*     <br>",fileres,fileres,fileres,fileres); */
                   8067: /*  else  */
1.338     brouard  8068: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=1+age+%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222     brouard  8069:    fflush(fichtm);
1.126     brouard  8070: 
1.225     brouard  8071:    m=pow(2,cptcoveff);
1.222     brouard  8072:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8073: 
1.317     brouard  8074:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8075: 
                   8076:   jj1=0;
                   8077: 
                   8078:    fprintf(fichtm," \n<ul>");
1.337     brouard  8079:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8080:      /* k1=nres; */
1.338     brouard  8081:      k1=TKresult[nres];
1.337     brouard  8082:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8083:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8084:      /*   continue; */
1.317     brouard  8085:      jj1++;
                   8086:      if (cptcovn > 0) {
                   8087:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8088:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8089:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8090:        }
                   8091:        fprintf(fichtm,"\">");
                   8092:        
                   8093:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8094:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8095:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8096:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8097:        }
                   8098:        if(invalidvarcomb[k1]){
                   8099:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8100:         continue;
                   8101:        }
                   8102:        fprintf(fichtm,"</a></li>");
                   8103:      } /* cptcovn >0 */
1.337     brouard  8104:    } /* End nres */
1.317     brouard  8105:    fprintf(fichtm," \n</ul>");
                   8106: 
1.222     brouard  8107:    jj1=0;
1.237     brouard  8108: 
1.241     brouard  8109:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8110:      /* k1=nres; */
1.338     brouard  8111:      k1=TKresult[nres];
                   8112:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8113:      /* for(k1=1; k1<=m;k1++){ */
                   8114:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8115:      /*   continue; */
1.222     brouard  8116:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8117:      jj1++;
1.126     brouard  8118:      if (cptcovn > 0) {
1.317     brouard  8119:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8120:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8121:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8122:        }
                   8123:        fprintf(fichtm,"\"</a>");
                   8124:        
1.126     brouard  8125:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8126:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8127:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8128:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8129:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8130:        }
1.237     brouard  8131: 
1.338     brouard  8132:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8133: 
1.222     brouard  8134:        if(invalidvarcomb[k1]){
                   8135:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8136:         continue;
                   8137:        }
1.337     brouard  8138:      } /* If cptcovn >0 */
1.126     brouard  8139:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8140:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8141: 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);
                   8142:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8143:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8144:      }
                   8145:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8146: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8147: true period expectancies (those weighted with period prevalences are also\
                   8148:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8149:  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);
                   8150:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8151:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8152:      /* } /\* end i1 *\/ */
1.241     brouard  8153:   }/* End nres */
1.222     brouard  8154:    fprintf(fichtm,"</ul>");
                   8155:    fflush(fichtm);
1.126     brouard  8156: }
                   8157: 
                   8158: /******************* Gnuplot file **************/
1.296     brouard  8159: 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  8160: 
                   8161:   char dirfileres[132],optfileres[132];
1.264     brouard  8162:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8163:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  8164:   int lv=0, vlv=0, kl=0;
1.130     brouard  8165:   int ng=0;
1.201     brouard  8166:   int vpopbased;
1.223     brouard  8167:   int ioffset; /* variable offset for columns */
1.270     brouard  8168:   int iyearc=1; /* variable column for year of projection  */
                   8169:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8170:   int nres=0; /* Index of resultline */
1.266     brouard  8171:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8172: 
1.126     brouard  8173: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8174: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8175: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8176: /*   } */
                   8177: 
                   8178:   /*#ifdef windows */
                   8179:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8180:   /*#endif */
1.225     brouard  8181:   m=pow(2,cptcoveff);
1.126     brouard  8182: 
1.274     brouard  8183:   /* diagram of the model */
                   8184:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8185:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8186:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8187:   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);
                   8188: 
1.343     brouard  8189:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=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,nlstate);
1.274     brouard  8190:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8191:   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);
                   8192:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8193:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8194:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8195:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8196: 
1.202     brouard  8197:   /* Contribution to likelihood */
                   8198:   /* Plot the probability implied in the likelihood */
1.223     brouard  8199:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8200:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8201:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8202:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8203: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8204:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8205: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8206:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8207:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8208:   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));
                   8209:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8210:   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));
                   8211:   for (i=1; i<= nlstate ; i ++) {
                   8212:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8213:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8214:     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);
                   8215:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8216:       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);
                   8217:     }
                   8218:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8219:   }
                   8220:   /* 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 */               
                   8221:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8222:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8223:   fprintf(ficgp,"\nset out;unset log\n");
                   8224:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8225: 
1.343     brouard  8226:   /* Plot the probability implied in the likelihood by covariate value */
                   8227:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8228:   /* if(debugILK==1){ */
                   8229:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8230:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8231:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
                   8232:     k=18+kf;/*offset because there are 18 columns in the ILK_ file */
1.343     brouard  8233:     for (i=1; i<= nlstate ; i ++) {
                   8234:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8235:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348   ! brouard  8236:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
        !          8237:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
        !          8238:        for (j=2; j<= nlstate+ndeath ; j ++) {
        !          8239:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
        !          8240:        }
        !          8241:       }else{
        !          8242:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
        !          8243:        for (j=2; j<= nlstate+ndeath ; j ++) {
        !          8244:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
        !          8245:        }
1.343     brouard  8246:       }
                   8247:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8248:     }
                   8249:   } /* End of each covariate dummy */
                   8250:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8251:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8252:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8253:      *  varying                   1     2                                 3       4        5
                   8254:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8255:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8256:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8257:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8258:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8259:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8260:      */
                   8261:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8262:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8263:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   8264:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8265:       /* printf(" %d",ipos); */
                   8266:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8267:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8268:       kk++; /* Position of the ncovv column in ILK_ */
                   8269:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8270:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   8271:        for (i=1; i<= nlstate ; i ++) {
                   8272:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8273:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8274: 
1.348   ! brouard  8275:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8276:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8277:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8278:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   8279:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8280:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   8281:            }
                   8282:          }else{
                   8283:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8284:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   8285:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8286:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   8287:            }
                   8288:          }
                   8289:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8290:        }
                   8291:       }/* End if dummy varying */
                   8292:     }else{ /*Product */
                   8293:       /* printf("*"); */
                   8294:       /* fprintf(ficresilk,"*"); */
                   8295:     }
                   8296:     iposold=ipos;
                   8297:   } /* For each time varying covariate */
                   8298:   /* } /\* debugILK==1 *\/ */
                   8299:   /* 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 */               
                   8300:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8301:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8302:   fprintf(ficgp,"\nset out;unset log\n");
                   8303:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8304: 
                   8305: 
                   8306:   
1.126     brouard  8307:   strcpy(dirfileres,optionfilefiname);
                   8308:   strcpy(optfileres,"vpl");
1.223     brouard  8309:   /* 1eme*/
1.238     brouard  8310:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8311:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8312:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8313:        k1=TKresult[nres];
1.338     brouard  8314:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8315:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8316:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8317:        /*   continue; */
1.238     brouard  8318:        /* We are interested in selected combination by the resultline */
1.246     brouard  8319:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8320:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8321:        strcpy(gplotlabel,"(");
1.337     brouard  8322:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8323:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8324:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8325: 
                   8326:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8327:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8328:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8329:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8330:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8331:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8332:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8333:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8334:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8335:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8336:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8337:        /* } */
                   8338:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8339:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8340:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8341:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8342:        }
                   8343:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8344:        /* printf("\n#\n"); */
1.238     brouard  8345:        fprintf(ficgp,"\n#\n");
                   8346:        if(invalidvarcomb[k1]){
1.260     brouard  8347:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8348:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8349:          continue;
                   8350:        }
1.235     brouard  8351:       
1.241     brouard  8352:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8353:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8354:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.338     brouard  8355:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8356:        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);
                   8357:        /* 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); */
                   8358:       /* k1-1 error should be nres-1*/
1.238     brouard  8359:        for (i=1; i<= nlstate ; i ++) {
                   8360:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8361:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8362:        }
1.288     brouard  8363:        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  8364:        for (i=1; i<= nlstate ; i ++) {
                   8365:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8366:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8367:        } 
1.260     brouard  8368:        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  8369:        for (i=1; i<= nlstate ; i ++) {
                   8370:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8371:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8372:        }  
1.265     brouard  8373:        /* 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)); */
                   8374:        
                   8375:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8376:         if(cptcoveff ==0){
1.271     brouard  8377:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8378:        }else{
                   8379:          kl=0;
                   8380:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8381:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8382:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8383:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8384:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8385:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8386:            vlv= nbcode[Tvaraff[k]][lv];
                   8387:            kl++;
                   8388:            /* 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 *\/ */
                   8389:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8390:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8391:            /* ''  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*/
                   8392:            if(k==cptcoveff){
                   8393:              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], \
                   8394:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8395:            }else{
                   8396:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8397:              kl++;
                   8398:            }
                   8399:          } /* end covariate */
                   8400:        } /* end if no covariate */
                   8401: 
1.296     brouard  8402:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8403:          /* 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  8404:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8405:          if(cptcoveff ==0){
1.245     brouard  8406:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8407:          }else{
                   8408:            kl=0;
                   8409:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8410:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8411:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8412:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8413:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8414:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8415:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8416:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8417:              kl++;
1.238     brouard  8418:              /* 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 *\/ */
                   8419:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8420:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8421:              /* ''  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*/
                   8422:              if(k==cptcoveff){
1.245     brouard  8423:                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  8424:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8425:              }else{
1.332     brouard  8426:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8427:                kl++;
                   8428:              }
                   8429:            } /* end covariate */
                   8430:          } /* end if no covariate */
1.296     brouard  8431:          if(prevbcast == 1){
1.268     brouard  8432:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8433:            /* k1-1 error should be nres-1*/
                   8434:            for (i=1; i<= nlstate ; i ++) {
                   8435:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8436:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8437:            }
1.271     brouard  8438:            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  8439:            for (i=1; i<= nlstate ; i ++) {
                   8440:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8441:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8442:            } 
1.276     brouard  8443:            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  8444:            for (i=1; i<= nlstate ; i ++) {
                   8445:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8446:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8447:            } 
1.274     brouard  8448:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8449:          } /* end if backprojcast */
1.296     brouard  8450:        } /* end if prevbcast */
1.276     brouard  8451:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8452:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8453:       } /* nres */
1.337     brouard  8454:     /* } /\* k1 *\/ */
1.201     brouard  8455:   } /* cpt */
1.235     brouard  8456: 
                   8457:   
1.126     brouard  8458:   /*2 eme*/
1.337     brouard  8459:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8460:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8461:       k1=TKresult[nres];
1.338     brouard  8462:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8463:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8464:       /*       continue; */
1.238     brouard  8465:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8466:       strcpy(gplotlabel,"(");
1.337     brouard  8467:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8468:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8469:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8470:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8471:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8472:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8473:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8474:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8475:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8476:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8477:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8478:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8479:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8480:       /* } */
                   8481:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8482:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8483:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8484:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8485:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8486:       }
1.264     brouard  8487:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8488:       fprintf(ficgp,"\n#\n");
1.223     brouard  8489:       if(invalidvarcomb[k1]){
                   8490:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8491:        continue;
                   8492:       }
1.219     brouard  8493:                        
1.241     brouard  8494:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8495:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8496:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8497:        if(vpopbased==0){
1.238     brouard  8498:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8499:        }else
1.238     brouard  8500:          fprintf(ficgp,"\nreplot ");
                   8501:        for (i=1; i<= nlstate+1 ; i ++) {
                   8502:          k=2*i;
1.261     brouard  8503:          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  8504:          for (j=1; j<= nlstate+1 ; j ++) {
                   8505:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8506:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8507:          }   
                   8508:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8509:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8510:          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  8511:          for (j=1; j<= nlstate+1 ; j ++) {
                   8512:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8513:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8514:          }   
                   8515:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8516:          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  8517:          for (j=1; j<= nlstate+1 ; j ++) {
                   8518:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8519:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8520:          }   
                   8521:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8522:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8523:        } /* state */
                   8524:       } /* vpopbased */
1.264     brouard  8525:       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  8526:     } /* end nres */
1.337     brouard  8527:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8528:        
                   8529:        
                   8530:   /*3eme*/
1.337     brouard  8531:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8532:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8533:       k1=TKresult[nres];
1.338     brouard  8534:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8535:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8536:       /*       continue; */
1.238     brouard  8537: 
1.332     brouard  8538:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8539:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8540:        strcpy(gplotlabel,"(");
1.337     brouard  8541:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8542:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8543:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8544:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8545:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8546:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8547:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8548:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8549:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8550:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8551:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8552:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8553:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8554:        /* } */
                   8555:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8556:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8557:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8558:        }
1.264     brouard  8559:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8560:        fprintf(ficgp,"\n#\n");
                   8561:        if(invalidvarcomb[k1]){
                   8562:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8563:          continue;
                   8564:        }
                   8565:                        
                   8566:        /*       k=2+nlstate*(2*cpt-2); */
                   8567:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8568:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8569:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8570:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8571: 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  8572:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8573:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8574:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8575:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8576:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8577:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8578:                                
1.238     brouard  8579:        */
                   8580:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8581:          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  8582:          /*    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  8583:                                
1.238     brouard  8584:        } 
1.261     brouard  8585:        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  8586:       }
1.264     brouard  8587:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8588:     } /* end nres */
1.337     brouard  8589:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8590:   
1.223     brouard  8591:   /* 4eme */
1.201     brouard  8592:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8593:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8594:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8595:       k1=TKresult[nres];
1.338     brouard  8596:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8597:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8598:       /*       continue; */
1.238     brouard  8599:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8600:        strcpy(gplotlabel,"(");
1.337     brouard  8601:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8602:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8603:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8604:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8605:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8606:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8607:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8608:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8609:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8610:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8611:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8612:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8613:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8614:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8615:        /* } */
                   8616:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8617:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8618:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8619:        }       
1.264     brouard  8620:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8621:        fprintf(ficgp,"\n#\n");
                   8622:        if(invalidvarcomb[k1]){
                   8623:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8624:          continue;
1.223     brouard  8625:        }
1.238     brouard  8626:       
1.241     brouard  8627:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8628:        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  8629:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8630: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8631:        k=3;
                   8632:        for (i=1; i<= nlstate ; i ++){
                   8633:          if(i==1){
                   8634:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8635:          }else{
                   8636:            fprintf(ficgp,", '' ");
                   8637:          }
                   8638:          l=(nlstate+ndeath)*(i-1)+1;
                   8639:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8640:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8641:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8642:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8643:        } /* nlstate */
1.264     brouard  8644:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8645:       } /* end cpt state*/ 
                   8646:     } /* end nres */
1.337     brouard  8647:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8648: 
1.220     brouard  8649: /* 5eme */
1.201     brouard  8650:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8651:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8652:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8653:       k1=TKresult[nres];
1.338     brouard  8654:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8655:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8656:       /*       continue; */
1.238     brouard  8657:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8658:        strcpy(gplotlabel,"(");
1.238     brouard  8659:        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);
1.337     brouard  8660:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8661:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8662:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8663:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8664:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8665:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8666:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8667:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8668:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8669:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8670:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8671:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8672:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8673:        /* } */
                   8674:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8675:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8676:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8677:        }       
1.264     brouard  8678:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8679:        fprintf(ficgp,"\n#\n");
                   8680:        if(invalidvarcomb[k1]){
                   8681:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8682:          continue;
                   8683:        }
1.227     brouard  8684:       
1.241     brouard  8685:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8686:        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  8687:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8688: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8689:        k=3;
                   8690:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8691:          if(j==1)
                   8692:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8693:          else
                   8694:            fprintf(ficgp,", '' ");
                   8695:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8696:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8697:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8698:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8699:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8700:        } /* nlstate */
                   8701:        fprintf(ficgp,", '' ");
                   8702:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8703:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8704:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8705:          if(j < nlstate)
                   8706:            fprintf(ficgp,"$%d +",k+l);
                   8707:          else
                   8708:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8709:        }
1.264     brouard  8710:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8711:       } /* end cpt state*/ 
1.337     brouard  8712:     /* } /\* end covariate *\/   */
1.238     brouard  8713:   } /* end nres */
1.227     brouard  8714:   
1.220     brouard  8715: /* 6eme */
1.202     brouard  8716:   /* CV preval stable (period) for each covariate */
1.337     brouard  8717:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8718:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8719:      k1=TKresult[nres];
1.338     brouard  8720:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8721:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8722:      /*  continue; */
1.255     brouard  8723:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8724:       strcpy(gplotlabel,"(");      
1.288     brouard  8725:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8726:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8727:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8728:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8729:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8730:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8731:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8732:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8733:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8734:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8735:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8736:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8737:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8738:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8739:       /* } */
                   8740:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8741:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8742:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8743:       }        
1.264     brouard  8744:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8745:       fprintf(ficgp,"\n#\n");
1.223     brouard  8746:       if(invalidvarcomb[k1]){
1.227     brouard  8747:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8748:        continue;
1.223     brouard  8749:       }
1.227     brouard  8750:       
1.241     brouard  8751:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8752:       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  8753:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8754: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8755:       k=3; /* Offset */
1.255     brouard  8756:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8757:        if(i==1)
                   8758:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8759:        else
                   8760:          fprintf(ficgp,", '' ");
1.255     brouard  8761:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8762:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8763:        for (j=2; j<= nlstate ; j ++)
                   8764:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8765:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8766:       } /* nlstate */
1.264     brouard  8767:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8768:     } /* end cpt state*/ 
                   8769:   } /* end covariate */  
1.227     brouard  8770:   
                   8771:   
1.220     brouard  8772: /* 7eme */
1.296     brouard  8773:   if(prevbcast == 1){
1.288     brouard  8774:     /* CV backward prevalence  for each covariate */
1.337     brouard  8775:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8776:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8777:       k1=TKresult[nres];
1.338     brouard  8778:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8779:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8780:       /*       continue; */
1.268     brouard  8781:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8782:        strcpy(gplotlabel,"(");      
1.288     brouard  8783:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8784:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8785:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8786:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8787:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8788:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8789:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8790:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8791:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8792:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8793:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8794:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8795:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8796:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8797:        /* } */
                   8798:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8799:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8800:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8801:        }       
1.264     brouard  8802:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8803:        fprintf(ficgp,"\n#\n");
                   8804:        if(invalidvarcomb[k1]){
                   8805:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8806:          continue;
                   8807:        }
                   8808:        
1.241     brouard  8809:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8810:        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  8811:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8812: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8813:        k=3; /* Offset */
1.268     brouard  8814:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8815:          if(i==1)
                   8816:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8817:          else
                   8818:            fprintf(ficgp,", '' ");
                   8819:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8820:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8821:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8822:          /* 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  8823:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8824:          /* for (j=2; j<= nlstate ; j ++) */
                   8825:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8826:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8827:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8828:        } /* nlstate */
1.264     brouard  8829:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8830:       } /* end cpt state*/ 
                   8831:     } /* end covariate */  
1.296     brouard  8832:   } /* End if prevbcast */
1.218     brouard  8833:   
1.223     brouard  8834:   /* 8eme */
1.218     brouard  8835:   if(prevfcast==1){
1.288     brouard  8836:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8837:     
1.337     brouard  8838:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8839:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8840:       k1=TKresult[nres];
1.338     brouard  8841:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8842:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8843:       /*       continue; */
1.211     brouard  8844:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8845:        strcpy(gplotlabel,"(");      
1.288     brouard  8846:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8847:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8848:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8849:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8850:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8851:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8852:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8853:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8854:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8855:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8856:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8857:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8858:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8859:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8860:        /* } */
                   8861:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8862:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8863:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8864:        }       
1.264     brouard  8865:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8866:        fprintf(ficgp,"\n#\n");
                   8867:        if(invalidvarcomb[k1]){
                   8868:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8869:          continue;
                   8870:        }
                   8871:        
                   8872:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8873:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8874:        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  8875:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8876: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8877: 
                   8878:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8879:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8880:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8881:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8882:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8883:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8884:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8885:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8886:          if(i==istart){
1.227     brouard  8887:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8888:          }else{
                   8889:            fprintf(ficgp,",\\\n '' ");
                   8890:          }
                   8891:          if(cptcoveff ==0){ /* No covariate */
                   8892:            ioffset=2; /* Age is in 2 */
                   8893:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8894:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8895:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8896:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8897:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8898:            if(i==nlstate+1){
1.270     brouard  8899:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8900:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8901:              fprintf(ficgp,",\\\n '' ");
                   8902:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8903:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8904:                     offyear,                           \
1.268     brouard  8905:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8906:            }else
1.227     brouard  8907:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8908:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8909:          }else{ /* more than 2 covariates */
1.270     brouard  8910:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8911:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8912:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8913:            iyearc=ioffset-1;
                   8914:            iagec=ioffset;
1.227     brouard  8915:            fprintf(ficgp," u %d:(",ioffset); 
                   8916:            kl=0;
                   8917:            strcpy(gplotcondition,"(");
                   8918:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8919:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8920:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8921:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8922:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8923:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8924:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8925:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8926:              kl++;
                   8927:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8928:              kl++;
                   8929:              if(k <cptcoveff && cptcoveff>1)
                   8930:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8931:            }
                   8932:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8933:            /* 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 *\/ */
                   8934:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8935:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8936:            /* ''  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*/
                   8937:            if(i==nlstate+1){
1.270     brouard  8938:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8939:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8940:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8941:              fprintf(ficgp," u %d:(",iagec); 
                   8942:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8943:                      iyearc, iagec, offyear,                           \
                   8944:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8945: /*  '' 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  8946:            }else{
                   8947:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8948:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8949:            }
                   8950:          } /* end if covariate */
                   8951:        } /* nlstate */
1.264     brouard  8952:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8953:       } /* end cpt state*/
                   8954:     } /* end covariate */
                   8955:   } /* End if prevfcast */
1.227     brouard  8956:   
1.296     brouard  8957:   if(prevbcast==1){
1.268     brouard  8958:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8959:     
1.337     brouard  8960:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8961:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8962:      k1=TKresult[nres];
1.338     brouard  8963:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8964:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8965:        /*      continue; */
1.268     brouard  8966:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8967:        strcpy(gplotlabel,"(");      
                   8968:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
1.337     brouard  8969:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8970:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8971:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8972:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8973:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8974:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8975:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8976:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8977:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8978:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8979:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8980:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8981:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8982:        /* } */
                   8983:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8984:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8985:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8986:        }       
                   8987:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8988:        fprintf(ficgp,"\n#\n");
                   8989:        if(invalidvarcomb[k1]){
                   8990:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8991:          continue;
                   8992:        }
                   8993:        
                   8994:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8995:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8996:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8997:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8998: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8999: 
                   9000:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9001:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9002:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9003:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9004:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9005:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9006:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9007:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9008:          if(i==istart){
                   9009:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9010:          }else{
                   9011:            fprintf(ficgp,",\\\n '' ");
                   9012:          }
                   9013:          if(cptcoveff ==0){ /* No covariate */
                   9014:            ioffset=2; /* Age is in 2 */
                   9015:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9016:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9017:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9018:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9019:            fprintf(ficgp," u %d:(", ioffset); 
                   9020:            if(i==nlstate+1){
1.270     brouard  9021:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9022:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9023:              fprintf(ficgp,",\\\n '' ");
                   9024:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9025:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9026:                     offbyear,                          \
                   9027:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9028:            }else
                   9029:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9030:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9031:          }else{ /* more than 2 covariates */
1.270     brouard  9032:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9033:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9034:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9035:            iyearc=ioffset-1;
                   9036:            iagec=ioffset;
1.268     brouard  9037:            fprintf(ficgp," u %d:(",ioffset); 
                   9038:            kl=0;
                   9039:            strcpy(gplotcondition,"(");
1.337     brouard  9040:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9041:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9042:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9043:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9044:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9045:                lv=Tvresult[nres][k];
                   9046:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9047:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9048:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9049:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9050:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9051:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9052:                kl++;
                   9053:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9054:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9055:                kl++;
1.338     brouard  9056:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9057:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9058:              }
1.268     brouard  9059:            }
                   9060:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9061:            /* 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 *\/ */
                   9062:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9063:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9064:            /* ''  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*/
                   9065:            if(i==nlstate+1){
1.270     brouard  9066:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9067:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9068:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9069:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9070:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9071:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9072:                      iyearc,iagec,offbyear,                            \
                   9073:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9074: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9075:            }else{
                   9076:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9077:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9078:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9079:            }
                   9080:          } /* end if covariate */
                   9081:        } /* nlstate */
                   9082:        fprintf(ficgp,"\nset out; unset label;\n");
                   9083:       } /* end cpt state*/
                   9084:     } /* end covariate */
1.296     brouard  9085:   } /* End if prevbcast */
1.268     brouard  9086:   
1.227     brouard  9087:   
1.238     brouard  9088:   /* 9eme writing MLE parameters */
                   9089:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9090:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9091:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9092:     for(k=1; k <=(nlstate+ndeath); k++){
                   9093:       if (k != i) {
1.227     brouard  9094:        fprintf(ficgp,"#   current state %d\n",k);
                   9095:        for(j=1; j <=ncovmodel; j++){
                   9096:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9097:          jk++; 
                   9098:        }
                   9099:        fprintf(ficgp,"\n");
1.126     brouard  9100:       }
                   9101:     }
1.223     brouard  9102:   }
1.187     brouard  9103:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9104:   
1.145     brouard  9105:   /*goto avoid;*/
1.238     brouard  9106:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9107:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9108:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9109:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9110:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9111:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9112:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9113:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9114:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9115:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9116:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9117:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9118:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9119:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9120:   fprintf(ficgp,"#\n");
1.223     brouard  9121:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9122:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9123:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9124:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9125:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9126:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9127:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9128:      /* k1=nres; */
1.338     brouard  9129:       k1=TKresult[nres];
                   9130:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9131:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9132:       strcpy(gplotlabel,"(");
1.276     brouard  9133:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9134:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9135:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9136:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9137:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9138:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9139:       }
                   9140:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9141:       /*       continue; */
                   9142:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9143:       /* strcpy(gplotlabel,"("); */
                   9144:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9145:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9146:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9147:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9148:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9149:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9150:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9151:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9152:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9153:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9154:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9155:       /* } */
                   9156:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9157:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9158:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9159:       /* }      */
1.264     brouard  9160:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9161:       fprintf(ficgp,"\n#\n");
1.264     brouard  9162:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9163:       fprintf(ficgp,"\nset key outside ");
                   9164:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9165:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9166:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9167:       if (ng==1){
                   9168:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9169:        fprintf(ficgp,"\nunset log y");
                   9170:       }else if (ng==2){
                   9171:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9172:        fprintf(ficgp,"\nset log y");
                   9173:       }else if (ng==3){
                   9174:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9175:        fprintf(ficgp,"\nset log y");
                   9176:       }else
                   9177:        fprintf(ficgp,"\nunset title ");
                   9178:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9179:       i=1;
                   9180:       for(k2=1; k2<=nlstate; k2++) {
                   9181:        k3=i;
                   9182:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9183:          if (k != k2){
                   9184:            switch( ng) {
                   9185:            case 1:
                   9186:              if(nagesqr==0)
                   9187:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9188:              else /* nagesqr =1 */
                   9189:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9190:              break;
                   9191:            case 2: /* ng=2 */
                   9192:              if(nagesqr==0)
                   9193:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9194:              else /* nagesqr =1 */
                   9195:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9196:              break;
                   9197:            case 3:
                   9198:              if(nagesqr==0)
                   9199:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9200:              else /* nagesqr =1 */
                   9201:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9202:              break;
                   9203:            }
                   9204:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9205:            ijp=1; /* product no age */
                   9206:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9207:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9208:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9209:              switch(Typevar[j]){
                   9210:              case 1:
                   9211:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9212:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9213:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9214:                      if(DummyV[j]==0){/* Bug valgrind */
                   9215:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9216:                      }else{ /* quantitative */
                   9217:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9218:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9219:                      }
                   9220:                      ij++;
1.268     brouard  9221:                    }
1.237     brouard  9222:                  }
1.329     brouard  9223:                }
                   9224:                break;
                   9225:              case 2:
                   9226:                if(cptcovprod >0){
                   9227:                  if(j==Tprod[ijp]) { /* */ 
                   9228:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9229:                    if(ijp <=cptcovprod) { /* Product */
                   9230:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9231:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9232:                          /* 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)]); */
                   9233:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9234:                        }else{ /* Vn is dummy and Vm is quanti */
                   9235:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9236:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9237:                        }
                   9238:                      }else{ /* Vn*Vm Vn is quanti */
                   9239:                        if(DummyV[Tvard[ijp][2]]==0){
                   9240:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9241:                        }else{ /* Both quanti */
                   9242:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9243:                        }
1.268     brouard  9244:                      }
1.329     brouard  9245:                      ijp++;
1.237     brouard  9246:                    }
1.329     brouard  9247:                  } /* end Tprod */
                   9248:                }
                   9249:                break;
                   9250:              case 0:
                   9251:                /* simple covariate */
1.264     brouard  9252:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9253:                if(Dummy[j]==0){
                   9254:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9255:                }else{ /* quantitative */
                   9256:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9257:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9258:                }
1.329     brouard  9259:               /* end simple */
                   9260:                break;
                   9261:              default:
                   9262:                break;
                   9263:              } /* end switch */
1.237     brouard  9264:            } /* end j */
1.329     brouard  9265:          }else{ /* k=k2 */
                   9266:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9267:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9268:            }else
                   9269:              i=i-ncovmodel;
1.223     brouard  9270:          }
1.227     brouard  9271:          
1.223     brouard  9272:          if(ng != 1){
                   9273:            fprintf(ficgp,")/(1");
1.227     brouard  9274:            
1.264     brouard  9275:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9276:              if(nagesqr==0)
1.264     brouard  9277:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9278:              else /* nagesqr =1 */
1.264     brouard  9279:                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  9280:               
1.223     brouard  9281:              ij=1;
1.329     brouard  9282:              ijp=1;
                   9283:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9284:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9285:                switch(Typevar[j]){
                   9286:                case 1:
                   9287:                  if(cptcovage >0){ 
                   9288:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9289:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9290:                        if(DummyV[j]==0){/* Bug valgrind */
                   9291:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9292:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9293:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9294:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9295:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9296:                        }else{ /* quantitative */
                   9297:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9298:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9299:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9300:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9301:                        }
                   9302:                        ij++;
                   9303:                      }
                   9304:                    }
                   9305:                  }
                   9306:                  break;
                   9307:                case 2:
                   9308:                  if(cptcovprod >0){
                   9309:                    if(j==Tprod[ijp]) { /* */ 
                   9310:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9311:                      if(ijp <=cptcovprod) { /* Product */
                   9312:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9313:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9314:                            /* 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)]); */
                   9315:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9316:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9317:                          }else{ /* Vn is dummy and Vm is quanti */
                   9318:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9319:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9320:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9321:                          }
                   9322:                        }else{ /* Vn*Vm Vn is quanti */
                   9323:                          if(DummyV[Tvard[ijp][2]]==0){
                   9324:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9325:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9326:                          }else{ /* Both quanti */
                   9327:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9328:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9329:                          } 
                   9330:                        }
                   9331:                        ijp++;
                   9332:                      }
                   9333:                    } /* end Tprod */
                   9334:                  } /* end if */
                   9335:                  break;
                   9336:                case 0: 
                   9337:                  /* simple covariate */
                   9338:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9339:                  if(Dummy[j]==0){
                   9340:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9341:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9342:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9343:                  }else{ /* quantitative */
                   9344:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9345:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9346:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9347:                  }
                   9348:                  /* end simple */
                   9349:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9350:                  break;
                   9351:                default:
                   9352:                  break;
                   9353:                } /* end switch */
1.223     brouard  9354:              }
                   9355:              fprintf(ficgp,")");
                   9356:            }
                   9357:            fprintf(ficgp,")");
                   9358:            if(ng ==2)
1.276     brouard  9359:              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  9360:            else /* ng= 3 */
1.276     brouard  9361:              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  9362:           }else{ /* end ng <> 1 */
1.223     brouard  9363:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9364:              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  9365:          }
                   9366:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9367:            fprintf(ficgp,",");
                   9368:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9369:            fprintf(ficgp,",");
                   9370:          i=i+ncovmodel;
                   9371:        } /* end k */
                   9372:       } /* end k2 */
1.276     brouard  9373:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9374:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9375:     } /* end resultline */
1.223     brouard  9376:   } /* end ng */
                   9377:   /* avoid: */
                   9378:   fflush(ficgp); 
1.126     brouard  9379: }  /* end gnuplot */
                   9380: 
                   9381: 
                   9382: /*************** Moving average **************/
1.219     brouard  9383: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9384:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9385:    
1.222     brouard  9386:    int i, cpt, cptcod;
                   9387:    int modcovmax =1;
                   9388:    int mobilavrange, mob;
                   9389:    int iage=0;
1.288     brouard  9390:    int firstA1=0, firstA2=0;
1.222     brouard  9391: 
1.266     brouard  9392:    double sum=0., sumr=0.;
1.222     brouard  9393:    double age;
1.266     brouard  9394:    double *sumnewp, *sumnewm, *sumnewmr;
                   9395:    double *agemingood, *agemaxgood; 
                   9396:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9397:   
                   9398:   
1.278     brouard  9399:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9400:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9401: 
                   9402:    sumnewp = vector(1,ncovcombmax);
                   9403:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9404:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9405:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9406:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9407:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9408:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9409: 
                   9410:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9411:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9412:      sumnewp[cptcod]=0.;
1.266     brouard  9413:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9414:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9415:    }
                   9416:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9417:   
1.266     brouard  9418:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9419:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9420:      else mobilavrange=mobilav;
                   9421:      for (age=bage; age<=fage; age++)
                   9422:        for (i=1; i<=nlstate;i++)
                   9423:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9424:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9425:      /* We keep the original values on the extreme ages bage, fage and for 
                   9426:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9427:        we use a 5 terms etc. until the borders are no more concerned. 
                   9428:      */ 
                   9429:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9430:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9431:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9432:           sumnewm[cptcod]=0.;
                   9433:           for (i=1; i<=nlstate;i++){
1.222     brouard  9434:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9435:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9436:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9437:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9438:             }
                   9439:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9440:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9441:           } /* end i */
                   9442:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9443:         } /* end cptcod */
1.222     brouard  9444:        }/* end age */
                   9445:      }/* end mob */
1.266     brouard  9446:    }else{
                   9447:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9448:      return -1;
1.266     brouard  9449:    }
                   9450: 
                   9451:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9452:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9453:      if(invalidvarcomb[cptcod]){
                   9454:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9455:        continue;
                   9456:      }
1.219     brouard  9457: 
1.266     brouard  9458:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9459:        sumnewm[cptcod]=0.;
                   9460:        sumnewmr[cptcod]=0.;
                   9461:        for (i=1; i<=nlstate;i++){
                   9462:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9463:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9464:        }
                   9465:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9466:         agemingoodr[cptcod]=age;
                   9467:        }
                   9468:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9469:           agemingood[cptcod]=age;
                   9470:        }
                   9471:      } /* age */
                   9472:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9473:        sumnewm[cptcod]=0.;
1.266     brouard  9474:        sumnewmr[cptcod]=0.;
1.222     brouard  9475:        for (i=1; i<=nlstate;i++){
                   9476:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9477:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9478:        }
                   9479:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9480:         agemaxgoodr[cptcod]=age;
1.222     brouard  9481:        }
                   9482:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9483:         agemaxgood[cptcod]=age;
                   9484:        }
                   9485:      } /* age */
                   9486:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9487:      /* but they will change */
1.288     brouard  9488:      firstA1=0;firstA2=0;
1.266     brouard  9489:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9490:        sumnewm[cptcod]=0.;
                   9491:        sumnewmr[cptcod]=0.;
                   9492:        for (i=1; i<=nlstate;i++){
                   9493:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9494:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9495:        }
                   9496:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9497:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9498:           agemaxgoodr[cptcod]=age;  /* age min */
                   9499:           for (i=1; i<=nlstate;i++)
                   9500:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9501:         }else{ /* bad we change the value with the values of good ages */
                   9502:           for (i=1; i<=nlstate;i++){
                   9503:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9504:           } /* i */
                   9505:         } /* end bad */
                   9506:        }else{
                   9507:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9508:           agemaxgood[cptcod]=age;
                   9509:         }else{ /* bad we change the value with the values of good ages */
                   9510:           for (i=1; i<=nlstate;i++){
                   9511:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9512:           } /* i */
                   9513:         } /* end bad */
                   9514:        }/* end else */
                   9515:        sum=0.;sumr=0.;
                   9516:        for (i=1; i<=nlstate;i++){
                   9517:         sum+=mobaverage[(int)age][i][cptcod];
                   9518:         sumr+=probs[(int)age][i][cptcod];
                   9519:        }
                   9520:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9521:         if(!firstA1){
                   9522:           firstA1=1;
                   9523:           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);
                   9524:         }
                   9525:         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  9526:        } /* end bad */
                   9527:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9528:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9529:         if(!firstA2){
                   9530:           firstA2=1;
                   9531:           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);
                   9532:         }
                   9533:         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  9534:        } /* end bad */
                   9535:      }/* age */
1.266     brouard  9536: 
                   9537:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9538:        sumnewm[cptcod]=0.;
1.266     brouard  9539:        sumnewmr[cptcod]=0.;
1.222     brouard  9540:        for (i=1; i<=nlstate;i++){
                   9541:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9542:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9543:        } 
                   9544:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9545:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9546:           agemingoodr[cptcod]=age;
                   9547:           for (i=1; i<=nlstate;i++)
                   9548:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9549:         }else{ /* bad we change the value with the values of good ages */
                   9550:           for (i=1; i<=nlstate;i++){
                   9551:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9552:           } /* i */
                   9553:         } /* end bad */
                   9554:        }else{
                   9555:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9556:           agemingood[cptcod]=age;
                   9557:         }else{ /* bad */
                   9558:           for (i=1; i<=nlstate;i++){
                   9559:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9560:           } /* i */
                   9561:         } /* end bad */
                   9562:        }/* end else */
                   9563:        sum=0.;sumr=0.;
                   9564:        for (i=1; i<=nlstate;i++){
                   9565:         sum+=mobaverage[(int)age][i][cptcod];
                   9566:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9567:        }
1.266     brouard  9568:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9569:         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  9570:        } /* end bad */
                   9571:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9572:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9573:         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  9574:        } /* end bad */
                   9575:      }/* age */
1.266     brouard  9576: 
1.222     brouard  9577:                
                   9578:      for (age=bage; age<=fage; age++){
1.235     brouard  9579:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9580:        sumnewp[cptcod]=0.;
                   9581:        sumnewm[cptcod]=0.;
                   9582:        for (i=1; i<=nlstate;i++){
                   9583:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9584:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9585:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9586:        }
                   9587:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9588:      }
                   9589:      /* printf("\n"); */
                   9590:      /* } */
1.266     brouard  9591: 
1.222     brouard  9592:      /* brutal averaging */
1.266     brouard  9593:      /* for (i=1; i<=nlstate;i++){ */
                   9594:      /*   for (age=1; age<=bage; age++){ */
                   9595:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9596:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9597:      /*   }     */
                   9598:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9599:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9600:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9601:      /*   } */
                   9602:      /* } /\* end i status *\/ */
                   9603:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9604:      /*   for (age=1; age<=AGESUP; age++){ */
                   9605:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9606:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9607:      /*   } */
                   9608:      /* } */
1.222     brouard  9609:    }/* end cptcod */
1.266     brouard  9610:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9611:    free_vector(agemaxgood,1, ncovcombmax);
                   9612:    free_vector(agemingood,1, ncovcombmax);
                   9613:    free_vector(agemingoodr,1, ncovcombmax);
                   9614:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9615:    free_vector(sumnewm,1, ncovcombmax);
                   9616:    free_vector(sumnewp,1, ncovcombmax);
                   9617:    return 0;
                   9618:  }/* End movingaverage */
1.218     brouard  9619:  
1.126     brouard  9620: 
1.296     brouard  9621:  
1.126     brouard  9622: /************** Forecasting ******************/
1.296     brouard  9623: /* 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)*/
                   9624: 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){
                   9625:   /* dateintemean, mean date of interviews
                   9626:      dateprojd, year, month, day of starting projection 
                   9627:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9628:      agemin, agemax range of age
                   9629:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9630:   */
1.296     brouard  9631:   /* double anprojd, mprojd, jprojd; */
                   9632:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9633:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9634:   double agec; /* generic age */
1.296     brouard  9635:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9636:   double *popeffectif,*popcount;
                   9637:   double ***p3mat;
1.218     brouard  9638:   /* double ***mobaverage; */
1.126     brouard  9639:   char fileresf[FILENAMELENGTH];
                   9640: 
                   9641:   agelim=AGESUP;
1.211     brouard  9642:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9643:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9644:      We still use firstpass and lastpass as another selection.
                   9645:   */
1.214     brouard  9646:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9647:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9648:  
1.201     brouard  9649:   strcpy(fileresf,"F_"); 
                   9650:   strcat(fileresf,fileresu);
1.126     brouard  9651:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9652:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9653:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9654:   }
1.235     brouard  9655:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9656:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9657: 
1.225     brouard  9658:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9659: 
                   9660: 
                   9661:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9662:   if (stepm<=12) stepsize=1;
                   9663:   if(estepm < stepm){
                   9664:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9665:   }
1.270     brouard  9666:   else{
                   9667:     hstepm=estepm;   
                   9668:   }
                   9669:   if(estepm > stepm){ /* Yes every two year */
                   9670:     stepsize=2;
                   9671:   }
1.296     brouard  9672:   hstepm=hstepm/stepm;
1.126     brouard  9673: 
1.296     brouard  9674:   
                   9675:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9676:   /*                              fractional in yp1 *\/ */
                   9677:   /* aintmean=yp; */
                   9678:   /* yp2=modf((yp1*12),&yp); */
                   9679:   /* mintmean=yp; */
                   9680:   /* yp1=modf((yp2*30.5),&yp); */
                   9681:   /* jintmean=yp; */
                   9682:   /* if(jintmean==0) jintmean=1; */
                   9683:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9684: 
1.296     brouard  9685: 
                   9686:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9687:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9688:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9689:   i1=pow(2,cptcoveff);
1.126     brouard  9690:   if (cptcovn < 1){i1=1;}
                   9691:   
1.296     brouard  9692:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9693:   
                   9694:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9695:   
1.126     brouard  9696: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9697:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9698:     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  9699:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9700:       continue;
1.227     brouard  9701:     if(invalidvarcomb[k]){
                   9702:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9703:       continue;
                   9704:     }
                   9705:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9706:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9707:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9708:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9709:     }
1.235     brouard  9710:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9711:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9712:     }
1.227     brouard  9713:     fprintf(ficresf," yearproj age");
                   9714:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9715:       for(i=1; i<=nlstate;i++)               
                   9716:        fprintf(ficresf," p%d%d",i,j);
                   9717:       fprintf(ficresf," wp.%d",j);
                   9718:     }
1.296     brouard  9719:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9720:       fprintf(ficresf,"\n");
1.296     brouard  9721:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9722:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9723:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9724:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9725:        nhstepm = nhstepm/hstepm; 
                   9726:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9727:        oldm=oldms;savm=savms;
1.268     brouard  9728:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9729:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9730:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9731:        for (h=0; h<=nhstepm; h++){
                   9732:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9733:            break;
                   9734:          }
                   9735:        }
                   9736:        fprintf(ficresf,"\n");
                   9737:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9738:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9739:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9740:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9741:        
                   9742:        for(j=1; j<=nlstate+ndeath;j++) {
                   9743:          ppij=0.;
                   9744:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9745:            if (mobilav>=1)
                   9746:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9747:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9748:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9749:            }
1.268     brouard  9750:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9751:          } /* end i */
                   9752:          fprintf(ficresf," %.3f", ppij);
                   9753:        }/* end j */
1.227     brouard  9754:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9755:       } /* end agec */
1.266     brouard  9756:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9757:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9758:     } /* end yearp */
                   9759:   } /* end  k */
1.219     brouard  9760:        
1.126     brouard  9761:   fclose(ficresf);
1.215     brouard  9762:   printf("End of Computing forecasting \n");
                   9763:   fprintf(ficlog,"End of Computing forecasting\n");
                   9764: 
1.126     brouard  9765: }
                   9766: 
1.269     brouard  9767: /************** Back Forecasting ******************/
1.296     brouard  9768:  /* 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){ */
                   9769:  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){
                   9770:   /* back1, year, month, day of starting backprojection
1.267     brouard  9771:      agemin, agemax range of age
                   9772:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9773:      anback2 year of end of backprojection (same day and month as back1).
                   9774:      prevacurrent and prev are prevalences.
1.267     brouard  9775:   */
                   9776:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9777:   double agec; /* generic age */
1.302     brouard  9778:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9779:   double *popeffectif,*popcount;
                   9780:   double ***p3mat;
                   9781:   /* double ***mobaverage; */
                   9782:   char fileresfb[FILENAMELENGTH];
                   9783:  
1.268     brouard  9784:   agelim=AGEINF;
1.267     brouard  9785:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9786:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9787:      We still use firstpass and lastpass as another selection.
                   9788:   */
                   9789:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9790:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9791: 
                   9792:   /*Do we need to compute prevalence again?*/
                   9793: 
                   9794:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9795:   
                   9796:   strcpy(fileresfb,"FB_");
                   9797:   strcat(fileresfb,fileresu);
                   9798:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9799:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9800:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9801:   }
                   9802:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9803:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9804:   
                   9805:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9806:   
                   9807:    
                   9808:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9809:   if (stepm<=12) stepsize=1;
                   9810:   if(estepm < stepm){
                   9811:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9812:   }
1.270     brouard  9813:   else{
                   9814:     hstepm=estepm;   
                   9815:   }
                   9816:   if(estepm >= stepm){ /* Yes every two year */
                   9817:     stepsize=2;
                   9818:   }
1.267     brouard  9819:   
                   9820:   hstepm=hstepm/stepm;
1.296     brouard  9821:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9822:   /*                              fractional in yp1 *\/ */
                   9823:   /* aintmean=yp; */
                   9824:   /* yp2=modf((yp1*12),&yp); */
                   9825:   /* mintmean=yp; */
                   9826:   /* yp1=modf((yp2*30.5),&yp); */
                   9827:   /* jintmean=yp; */
                   9828:   /* if(jintmean==0) jintmean=1; */
                   9829:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9830:   
                   9831:   i1=pow(2,cptcoveff);
                   9832:   if (cptcovn < 1){i1=1;}
                   9833:   
1.296     brouard  9834:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9835:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9836:   
                   9837:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9838:   
                   9839:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9840:   for(k=1; k<=i1;k++){
                   9841:     if(i1 != 1 && TKresult[nres]!= k)
                   9842:       continue;
                   9843:     if(invalidvarcomb[k]){
                   9844:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9845:       continue;
                   9846:     }
1.268     brouard  9847:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9848:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9849:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9850:     }
                   9851:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9852:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9853:     }
                   9854:     fprintf(ficresfb," yearbproj age");
                   9855:     for(j=1; j<=nlstate+ndeath;j++){
                   9856:       for(i=1; i<=nlstate;i++)
1.268     brouard  9857:        fprintf(ficresfb," b%d%d",i,j);
                   9858:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9859:     }
1.296     brouard  9860:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9861:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9862:       fprintf(ficresfb,"\n");
1.296     brouard  9863:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9864:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9865:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9866:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9867:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9868:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9869:        nhstepm = nhstepm/hstepm;
                   9870:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9871:        oldm=oldms;savm=savms;
1.268     brouard  9872:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9873:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9874:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9875:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9876:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9877:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9878:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9879:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9880:            break;
                   9881:          }
                   9882:        }
                   9883:        fprintf(ficresfb,"\n");
                   9884:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9885:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9886:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9887:        for(i=1; i<=nlstate+ndeath;i++) {
                   9888:          ppij=0.;ppi=0.;
                   9889:          for(j=1; j<=nlstate;j++) {
                   9890:            /* if (mobilav==1) */
1.269     brouard  9891:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9892:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9893:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9894:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9895:              /* else { */
                   9896:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9897:              /* } */
1.268     brouard  9898:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9899:          } /* end j */
                   9900:          if(ppi <0.99){
                   9901:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9902:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9903:          }
                   9904:          fprintf(ficresfb," %.3f", ppij);
                   9905:        }/* end j */
1.267     brouard  9906:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9907:       } /* end agec */
                   9908:     } /* end yearp */
                   9909:   } /* end k */
1.217     brouard  9910:   
1.267     brouard  9911:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9912:   
1.267     brouard  9913:   fclose(ficresfb);
                   9914:   printf("End of Computing Back forecasting \n");
                   9915:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9916:        
1.267     brouard  9917: }
1.217     brouard  9918: 
1.269     brouard  9919: /* Variance of prevalence limit: varprlim */
                   9920:  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  9921:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9922:  
                   9923:    char fileresvpl[FILENAMELENGTH];  
                   9924:    FILE *ficresvpl;
                   9925:    double **oldm, **savm;
                   9926:    double **varpl; /* Variances of prevalence limits by age */   
                   9927:    int i1, k, nres, j ;
                   9928:    
                   9929:     strcpy(fileresvpl,"VPL_");
                   9930:     strcat(fileresvpl,fileresu);
                   9931:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9932:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9933:       exit(0);
                   9934:     }
1.288     brouard  9935:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9936:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9937:     
                   9938:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9939:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9940:     
                   9941:     i1=pow(2,cptcoveff);
                   9942:     if (cptcovn < 1){i1=1;}
                   9943: 
1.337     brouard  9944:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9945:        k=TKresult[nres];
1.338     brouard  9946:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9947:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9948:       if(i1 != 1 && TKresult[nres]!= k)
                   9949:        continue;
                   9950:       fprintf(ficresvpl,"\n#****** ");
                   9951:       printf("\n#****** ");
                   9952:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9953:       for(j=1;j<=cptcovs;j++) {
                   9954:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9955:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9956:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9957:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9958:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9959:       }
1.337     brouard  9960:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9961:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9962:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9963:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9964:       /* }      */
1.269     brouard  9965:       fprintf(ficresvpl,"******\n");
                   9966:       printf("******\n");
                   9967:       fprintf(ficlog,"******\n");
                   9968:       
                   9969:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9970:       oldm=oldms;savm=savms;
                   9971:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9972:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9973:       /*}*/
                   9974:     }
                   9975:     
                   9976:     fclose(ficresvpl);
1.288     brouard  9977:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9978:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9979: 
                   9980:  }
                   9981: /* Variance of back prevalence: varbprlim */
                   9982:  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){
                   9983:       /*------- Variance of back (stable) prevalence------*/
                   9984: 
                   9985:    char fileresvbl[FILENAMELENGTH];  
                   9986:    FILE  *ficresvbl;
                   9987: 
                   9988:    double **oldm, **savm;
                   9989:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9990:    int i1, k, nres, j ;
                   9991: 
                   9992:    strcpy(fileresvbl,"VBL_");
                   9993:    strcat(fileresvbl,fileresu);
                   9994:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9995:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9996:      exit(0);
                   9997:    }
                   9998:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9999:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10000:    
                   10001:    
                   10002:    i1=pow(2,cptcoveff);
                   10003:    if (cptcovn < 1){i1=1;}
                   10004:    
1.337     brouard  10005:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10006:      k=TKresult[nres];
1.338     brouard  10007:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10008:     /* for(k=1; k<=i1;k++){ */
                   10009:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10010:     /*          continue; */
1.269     brouard  10011:        fprintf(ficresvbl,"\n#****** ");
                   10012:        printf("\n#****** ");
                   10013:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10014:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10015:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10016:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10017:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10018:        /* for(j=1;j<=cptcoveff;j++) { */
                   10019:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10020:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10021:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10022:        /* } */
                   10023:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10024:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10025:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10026:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10027:        }
                   10028:        fprintf(ficresvbl,"******\n");
                   10029:        printf("******\n");
                   10030:        fprintf(ficlog,"******\n");
                   10031:        
                   10032:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10033:        oldm=oldms;savm=savms;
                   10034:        
                   10035:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10036:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10037:        /*}*/
                   10038:      }
                   10039:    
                   10040:    fclose(ficresvbl);
                   10041:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10042:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10043: 
                   10044:  } /* End of varbprlim */
                   10045: 
1.126     brouard  10046: /************** Forecasting *****not tested NB*************/
1.227     brouard  10047: /* 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  10048:   
1.227     brouard  10049: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10050: /*   int *popage; */
                   10051: /*   double calagedatem, agelim, kk1, kk2; */
                   10052: /*   double *popeffectif,*popcount; */
                   10053: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10054: /*   /\* double ***mobaverage; *\/ */
                   10055: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10056: 
1.227     brouard  10057: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10058: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10059: /*   agelim=AGESUP; */
                   10060: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10061:   
1.227     brouard  10062: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10063:   
                   10064:   
1.227     brouard  10065: /*   strcpy(filerespop,"POP_");  */
                   10066: /*   strcat(filerespop,fileresu); */
                   10067: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10068: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10069: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10070: /*   } */
                   10071: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10072: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10073: 
1.227     brouard  10074: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10075: 
1.227     brouard  10076: /*   /\* if (mobilav!=0) { *\/ */
                   10077: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10078: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10079: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10080: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10081: /*   /\*   } *\/ */
                   10082: /*   /\* } *\/ */
1.126     brouard  10083: 
1.227     brouard  10084: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10085: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10086:   
1.227     brouard  10087: /*   agelim=AGESUP; */
1.126     brouard  10088:   
1.227     brouard  10089: /*   hstepm=1; */
                   10090: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10091:        
1.227     brouard  10092: /*   if (popforecast==1) { */
                   10093: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10094: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10095: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10096: /*     }  */
                   10097: /*     popage=ivector(0,AGESUP); */
                   10098: /*     popeffectif=vector(0,AGESUP); */
                   10099: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10100:     
1.227     brouard  10101: /*     i=1;    */
                   10102: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10103:     
1.227     brouard  10104: /*     imx=i; */
                   10105: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10106: /*   } */
1.218     brouard  10107:   
1.227     brouard  10108: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10109: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10110: /*       k=k+1; */
                   10111: /*       fprintf(ficrespop,"\n#******"); */
                   10112: /*       for(j=1;j<=cptcoveff;j++) { */
                   10113: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10114: /*       } */
                   10115: /*       fprintf(ficrespop,"******\n"); */
                   10116: /*       fprintf(ficrespop,"# Age"); */
                   10117: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10118: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10119:       
1.227     brouard  10120: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10121: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10122:        
1.227     brouard  10123: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10124: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10125: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10126:          
1.227     brouard  10127: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10128: /*       oldm=oldms;savm=savms; */
                   10129: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10130:          
1.227     brouard  10131: /*       for (h=0; h<=nhstepm; h++){ */
                   10132: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10133: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10134: /*         }  */
                   10135: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10136: /*           kk1=0.;kk2=0; */
                   10137: /*           for(i=1; i<=nlstate;i++) {               */
                   10138: /*             if (mobilav==1)  */
                   10139: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10140: /*             else { */
                   10141: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10142: /*             } */
                   10143: /*           } */
                   10144: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10145: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10146: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10147: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10148: /*           } */
                   10149: /*         } */
                   10150: /*         for(i=1; i<=nlstate;i++){ */
                   10151: /*           kk1=0.; */
                   10152: /*           for(j=1; j<=nlstate;j++){ */
                   10153: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10154: /*           } */
                   10155: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10156: /*         } */
1.218     brouard  10157:            
1.227     brouard  10158: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10159: /*           for(j=1; j<=nlstate;j++)  */
                   10160: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10161: /*       } */
                   10162: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10163: /*     } */
                   10164: /*       } */
1.218     brouard  10165:       
1.227     brouard  10166: /*       /\******\/ */
1.218     brouard  10167:       
1.227     brouard  10168: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10169: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10170: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10171: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10172: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10173:          
1.227     brouard  10174: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10175: /*       oldm=oldms;savm=savms; */
                   10176: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10177: /*       for (h=0; h<=nhstepm; h++){ */
                   10178: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10179: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10180: /*         }  */
                   10181: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10182: /*           kk1=0.;kk2=0; */
                   10183: /*           for(i=1; i<=nlstate;i++) {               */
                   10184: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10185: /*           } */
                   10186: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10187: /*         } */
                   10188: /*       } */
                   10189: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10190: /*     } */
                   10191: /*       } */
                   10192: /*     }  */
                   10193: /*   } */
1.218     brouard  10194:   
1.227     brouard  10195: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10196:   
1.227     brouard  10197: /*   if (popforecast==1) { */
                   10198: /*     free_ivector(popage,0,AGESUP); */
                   10199: /*     free_vector(popeffectif,0,AGESUP); */
                   10200: /*     free_vector(popcount,0,AGESUP); */
                   10201: /*   } */
                   10202: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10203: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10204: /*   fclose(ficrespop); */
                   10205: /* } /\* End of popforecast *\/ */
1.218     brouard  10206:  
1.126     brouard  10207: int fileappend(FILE *fichier, char *optionfich)
                   10208: {
                   10209:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10210:     printf("Problem with file: %s\n", optionfich);
                   10211:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10212:     return (0);
                   10213:   }
                   10214:   fflush(fichier);
                   10215:   return (1);
                   10216: }
                   10217: 
                   10218: 
                   10219: /**************** function prwizard **********************/
                   10220: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10221: {
                   10222: 
                   10223:   /* Wizard to print covariance matrix template */
                   10224: 
1.164     brouard  10225:   char ca[32], cb[32];
                   10226:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10227:   int numlinepar;
                   10228: 
                   10229:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10230:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10231:   for(i=1; i <=nlstate; i++){
                   10232:     jj=0;
                   10233:     for(j=1; j <=nlstate+ndeath; j++){
                   10234:       if(j==i) continue;
                   10235:       jj++;
                   10236:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10237:       printf("%1d%1d",i,j);
                   10238:       fprintf(ficparo,"%1d%1d",i,j);
                   10239:       for(k=1; k<=ncovmodel;k++){
                   10240:        /*        printf(" %lf",param[i][j][k]); */
                   10241:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10242:        printf(" 0.");
                   10243:        fprintf(ficparo," 0.");
                   10244:       }
                   10245:       printf("\n");
                   10246:       fprintf(ficparo,"\n");
                   10247:     }
                   10248:   }
                   10249:   printf("# Scales (for hessian or gradient estimation)\n");
                   10250:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10251:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10252:   for(i=1; i <=nlstate; i++){
                   10253:     jj=0;
                   10254:     for(j=1; j <=nlstate+ndeath; j++){
                   10255:       if(j==i) continue;
                   10256:       jj++;
                   10257:       fprintf(ficparo,"%1d%1d",i,j);
                   10258:       printf("%1d%1d",i,j);
                   10259:       fflush(stdout);
                   10260:       for(k=1; k<=ncovmodel;k++){
                   10261:        /*      printf(" %le",delti3[i][j][k]); */
                   10262:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10263:        printf(" 0.");
                   10264:        fprintf(ficparo," 0.");
                   10265:       }
                   10266:       numlinepar++;
                   10267:       printf("\n");
                   10268:       fprintf(ficparo,"\n");
                   10269:     }
                   10270:   }
                   10271:   printf("# Covariance matrix\n");
                   10272: /* # 121 Var(a12)\n\ */
                   10273: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10274: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10275: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10276: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10277: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10278: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10279: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10280:   fflush(stdout);
                   10281:   fprintf(ficparo,"# Covariance matrix\n");
                   10282:   /* # 121 Var(a12)\n\ */
                   10283:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10284:   /* #   ...\n\ */
                   10285:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10286:   
                   10287:   for(itimes=1;itimes<=2;itimes++){
                   10288:     jj=0;
                   10289:     for(i=1; i <=nlstate; i++){
                   10290:       for(j=1; j <=nlstate+ndeath; j++){
                   10291:        if(j==i) continue;
                   10292:        for(k=1; k<=ncovmodel;k++){
                   10293:          jj++;
                   10294:          ca[0]= k+'a'-1;ca[1]='\0';
                   10295:          if(itimes==1){
                   10296:            printf("#%1d%1d%d",i,j,k);
                   10297:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10298:          }else{
                   10299:            printf("%1d%1d%d",i,j,k);
                   10300:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10301:            /*  printf(" %.5le",matcov[i][j]); */
                   10302:          }
                   10303:          ll=0;
                   10304:          for(li=1;li <=nlstate; li++){
                   10305:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10306:              if(lj==li) continue;
                   10307:              for(lk=1;lk<=ncovmodel;lk++){
                   10308:                ll++;
                   10309:                if(ll<=jj){
                   10310:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10311:                  if(ll<jj){
                   10312:                    if(itimes==1){
                   10313:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10314:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10315:                    }else{
                   10316:                      printf(" 0.");
                   10317:                      fprintf(ficparo," 0.");
                   10318:                    }
                   10319:                  }else{
                   10320:                    if(itimes==1){
                   10321:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10322:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10323:                    }else{
                   10324:                      printf(" 0.");
                   10325:                      fprintf(ficparo," 0.");
                   10326:                    }
                   10327:                  }
                   10328:                }
                   10329:              } /* end lk */
                   10330:            } /* end lj */
                   10331:          } /* end li */
                   10332:          printf("\n");
                   10333:          fprintf(ficparo,"\n");
                   10334:          numlinepar++;
                   10335:        } /* end k*/
                   10336:       } /*end j */
                   10337:     } /* end i */
                   10338:   } /* end itimes */
                   10339: 
                   10340: } /* end of prwizard */
                   10341: /******************* Gompertz Likelihood ******************************/
                   10342: double gompertz(double x[])
                   10343: { 
1.302     brouard  10344:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10345:   int i,n=0; /* n is the size of the sample */
                   10346: 
1.220     brouard  10347:   for (i=1;i<=imx ; i++) {
1.126     brouard  10348:     sump=sump+weight[i];
                   10349:     /*    sump=sump+1;*/
                   10350:     num=num+1;
                   10351:   }
1.302     brouard  10352:   L=0.0;
                   10353:   /* agegomp=AGEGOMP; */
1.126     brouard  10354:   /* for (i=0; i<=imx; i++) 
                   10355:      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]);*/
                   10356: 
1.302     brouard  10357:   for (i=1;i<=imx ; i++) {
                   10358:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10359:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10360:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10361:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10362:      * +
                   10363:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10364:      */
                   10365:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10366:        if (cens[i] == 1){
                   10367:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10368:        } else if (cens[i] == 0){
1.126     brouard  10369:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10370:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10371:       } else
                   10372:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10373:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10374:        L=L+A*weight[i];
1.126     brouard  10375:        /*      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  10376:      }
                   10377:   }
1.126     brouard  10378: 
1.302     brouard  10379:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10380:  
                   10381:   return -2*L*num/sump;
                   10382: }
                   10383: 
1.136     brouard  10384: #ifdef GSL
                   10385: /******************* Gompertz_f Likelihood ******************************/
                   10386: double gompertz_f(const gsl_vector *v, void *params)
                   10387: { 
1.302     brouard  10388:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10389:   double *x= (double *) v->data;
                   10390:   int i,n=0; /* n is the size of the sample */
                   10391: 
                   10392:   for (i=0;i<=imx-1 ; i++) {
                   10393:     sump=sump+weight[i];
                   10394:     /*    sump=sump+1;*/
                   10395:     num=num+1;
                   10396:   }
                   10397:  
                   10398:  
                   10399:   /* for (i=0; i<=imx; i++) 
                   10400:      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]);*/
                   10401:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10402:   for (i=1;i<=imx ; i++)
                   10403:     {
                   10404:       if (cens[i] == 1 && wav[i]>1)
                   10405:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10406:       
                   10407:       if (cens[i] == 0 && wav[i]>1)
                   10408:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10409:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10410:       
                   10411:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10412:       if (wav[i] > 1 ) { /* ??? */
                   10413:        LL=LL+A*weight[i];
                   10414:        /*      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]);*/
                   10415:       }
                   10416:     }
                   10417: 
                   10418:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10419:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10420:  
                   10421:   return -2*LL*num/sump;
                   10422: }
                   10423: #endif
                   10424: 
1.126     brouard  10425: /******************* Printing html file ***********/
1.201     brouard  10426: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10427:                  int lastpass, int stepm, int weightopt, char model[],\
                   10428:                  int imx,  double p[],double **matcov,double agemortsup){
                   10429:   int i,k;
                   10430: 
                   10431:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10432:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10433:   for (i=1;i<=2;i++) 
                   10434:     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  10435:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10436:   fprintf(fichtm,"</ul>");
                   10437: 
                   10438: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10439: 
                   10440:  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>");
                   10441: 
                   10442:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10443:    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]);
                   10444: 
                   10445:  
                   10446:   fflush(fichtm);
                   10447: }
                   10448: 
                   10449: /******************* Gnuplot file **************/
1.201     brouard  10450: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10451: 
                   10452:   char dirfileres[132],optfileres[132];
1.164     brouard  10453: 
1.126     brouard  10454:   int ng;
                   10455: 
                   10456: 
                   10457:   /*#ifdef windows */
                   10458:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10459:     /*#endif */
                   10460: 
                   10461: 
                   10462:   strcpy(dirfileres,optionfilefiname);
                   10463:   strcpy(optfileres,"vpl");
1.199     brouard  10464:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10465:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10466:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10467:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10468:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10469: 
                   10470: } 
                   10471: 
1.136     brouard  10472: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10473: {
1.126     brouard  10474: 
1.136     brouard  10475:   /*-------- data file ----------*/
                   10476:   FILE *fic;
                   10477:   char dummy[]="                         ";
1.240     brouard  10478:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10479:   int lstra;
1.136     brouard  10480:   int linei, month, year,iout;
1.302     brouard  10481:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10482:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10483:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10484:   char *stratrunc;
1.223     brouard  10485: 
1.240     brouard  10486:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10487:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10488:   for(v=1;v<NCOVMAX;v++){
                   10489:     DummyV[v]=0;
                   10490:     FixedV[v]=0;
                   10491:   }
1.126     brouard  10492: 
1.240     brouard  10493:   for(v=1; v <=ncovcol;v++){
                   10494:     DummyV[v]=0;
                   10495:     FixedV[v]=0;
                   10496:   }
                   10497:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10498:     DummyV[v]=1;
                   10499:     FixedV[v]=0;
                   10500:   }
                   10501:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10502:     DummyV[v]=0;
                   10503:     FixedV[v]=1;
                   10504:   }
                   10505:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10506:     DummyV[v]=1;
                   10507:     FixedV[v]=1;
                   10508:   }
                   10509:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10510:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10511:     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]);
                   10512:   }
1.339     brouard  10513:   
                   10514:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10515:   
1.136     brouard  10516:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10517:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10518:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10519:   }
1.126     brouard  10520: 
1.302     brouard  10521:     /* Is it a BOM UTF-8 Windows file? */
                   10522:   /* First data line */
                   10523:   linei=0;
                   10524:   while(fgets(line, MAXLINE, fic)) {
                   10525:     noffset=0;
                   10526:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10527:     {
                   10528:       noffset=noffset+3;
                   10529:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10530:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10531:       fflush(ficlog); return 1;
                   10532:     }
                   10533:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10534:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10535:     {
                   10536:       noffset=noffset+2;
1.304     brouard  10537:       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);
                   10538:       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  10539:       fflush(ficlog); return 1;
                   10540:     }
                   10541:     else if( line[0] == 0 && line[1] == 0)
                   10542:     {
                   10543:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10544:        noffset=noffset+4;
1.304     brouard  10545:        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);
                   10546:        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  10547:        fflush(ficlog); return 1;
                   10548:       }
                   10549:     } else{
                   10550:       ;/*printf(" Not a BOM file\n");*/
                   10551:     }
                   10552:         /* If line starts with a # it is a comment */
                   10553:     if (line[noffset] == '#') {
                   10554:       linei=linei+1;
                   10555:       break;
                   10556:     }else{
                   10557:       break;
                   10558:     }
                   10559:   }
                   10560:   fclose(fic);
                   10561:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10562:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10563:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10564:   }
                   10565:   /* Not a Bom file */
                   10566:   
1.136     brouard  10567:   i=1;
                   10568:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10569:     linei=linei+1;
                   10570:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10571:       if(line[j] == '\t')
                   10572:        line[j] = ' ';
                   10573:     }
                   10574:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10575:       ;
                   10576:     };
                   10577:     line[j+1]=0;  /* Trims blanks at end of line */
                   10578:     if(line[0]=='#'){
                   10579:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10580:       printf("Comment line\n%s\n",line);
                   10581:       continue;
                   10582:     }
                   10583:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10584:     strcpy(line, linetmp);
1.223     brouard  10585:     
                   10586:     /* Loops on waves */
                   10587:     for (j=maxwav;j>=1;j--){
                   10588:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10589:        cutv(stra, strb, line, ' '); 
                   10590:        if(strb[0]=='.') { /* Missing value */
                   10591:          lval=-1;
                   10592:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10593:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10594:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10595:            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);
                   10596:            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);
                   10597:            return 1;
                   10598:          }
                   10599:        }else{
                   10600:          errno=0;
                   10601:          /* what_kind_of_number(strb); */
                   10602:          dval=strtod(strb,&endptr); 
                   10603:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10604:          /* if(strb != endptr && *endptr == '\0') */
                   10605:          /*    dval=dlval; */
                   10606:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10607:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10608:            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);
                   10609:            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);
                   10610:            return 1;
                   10611:          }
                   10612:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10613:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10614:        }
                   10615:        strcpy(line,stra);
1.223     brouard  10616:       }/* end loop ntqv */
1.225     brouard  10617:       
1.223     brouard  10618:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10619:        cutv(stra, strb, line, ' '); 
                   10620:        if(strb[0]=='.') { /* Missing value */
                   10621:          lval=-1;
                   10622:        }else{
                   10623:          errno=0;
                   10624:          lval=strtol(strb,&endptr,10); 
                   10625:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10626:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10627:            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);
                   10628:            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);
                   10629:            return 1;
                   10630:          }
                   10631:        }
                   10632:        if(lval <-1 || lval >1){
                   10633:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10634:  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  10635:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10636:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10637:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10638:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10639:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10640:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10641:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10642:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10643:  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  10644:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10645:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10646:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10647:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10648:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10649:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10650:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10651:          return 1;
                   10652:        }
1.341     brouard  10653:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10654:        strcpy(line,stra);
1.223     brouard  10655:       }/* end loop ntv */
1.225     brouard  10656:       
1.223     brouard  10657:       /* Statuses  at wave */
1.137     brouard  10658:       cutv(stra, strb, line, ' '); 
1.223     brouard  10659:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10660:        lval=-1;
1.136     brouard  10661:       }else{
1.238     brouard  10662:        errno=0;
                   10663:        lval=strtol(strb,&endptr,10); 
                   10664:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10665:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10666:          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);
                   10667:          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);
                   10668:          return 1;
                   10669:        }else if( lval==0 || lval > nlstate+ndeath){
1.348   ! brouard  10670:          printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
        !          10671:          fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
1.238     brouard  10672:          return 1;
                   10673:        }
1.136     brouard  10674:       }
1.225     brouard  10675:       
1.136     brouard  10676:       s[j][i]=lval;
1.225     brouard  10677:       
1.223     brouard  10678:       /* Date of Interview */
1.136     brouard  10679:       strcpy(line,stra);
                   10680:       cutv(stra, strb,line,' ');
1.169     brouard  10681:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10682:       }
1.169     brouard  10683:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10684:        month=99;
                   10685:        year=9999;
1.136     brouard  10686:       }else{
1.225     brouard  10687:        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);
                   10688:        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);
                   10689:        return 1;
1.136     brouard  10690:       }
                   10691:       anint[j][i]= (double) year; 
1.302     brouard  10692:       mint[j][i]= (double)month;
                   10693:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10694:       /*       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]); */
                   10695:       /*       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]); */
                   10696:       /* } */
1.136     brouard  10697:       strcpy(line,stra);
1.223     brouard  10698:     } /* End loop on waves */
1.225     brouard  10699:     
1.223     brouard  10700:     /* Date of death */
1.136     brouard  10701:     cutv(stra, strb,line,' '); 
1.169     brouard  10702:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10703:     }
1.169     brouard  10704:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10705:       month=99;
                   10706:       year=9999;
                   10707:     }else{
1.141     brouard  10708:       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  10709:       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);
                   10710:       return 1;
1.136     brouard  10711:     }
                   10712:     andc[i]=(double) year; 
                   10713:     moisdc[i]=(double) month; 
                   10714:     strcpy(line,stra);
                   10715:     
1.223     brouard  10716:     /* Date of birth */
1.136     brouard  10717:     cutv(stra, strb,line,' '); 
1.169     brouard  10718:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10719:     }
1.169     brouard  10720:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10721:       month=99;
                   10722:       year=9999;
                   10723:     }else{
1.141     brouard  10724:       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);
                   10725:       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  10726:       return 1;
1.136     brouard  10727:     }
                   10728:     if (year==9999) {
1.141     brouard  10729:       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);
                   10730:       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  10731:       return 1;
                   10732:       
1.136     brouard  10733:     }
                   10734:     annais[i]=(double)(year);
1.302     brouard  10735:     moisnais[i]=(double)(month);
                   10736:     for (j=1;j<=maxwav;j++){
                   10737:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10738:        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]);
                   10739:        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]);
                   10740:       }
                   10741:     }
                   10742: 
1.136     brouard  10743:     strcpy(line,stra);
1.225     brouard  10744:     
1.223     brouard  10745:     /* Sample weight */
1.136     brouard  10746:     cutv(stra, strb,line,' '); 
                   10747:     errno=0;
                   10748:     dval=strtod(strb,&endptr); 
                   10749:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10750:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10751:       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  10752:       fflush(ficlog);
                   10753:       return 1;
                   10754:     }
                   10755:     weight[i]=dval; 
                   10756:     strcpy(line,stra);
1.225     brouard  10757:     
1.223     brouard  10758:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10759:       cutv(stra, strb, line, ' '); 
                   10760:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10761:        lval=-1;
1.311     brouard  10762:        coqvar[iv][i]=NAN; 
                   10763:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10764:       }else{
1.225     brouard  10765:        errno=0;
                   10766:        /* what_kind_of_number(strb); */
                   10767:        dval=strtod(strb,&endptr);
                   10768:        /* if(strb != endptr && *endptr == '\0') */
                   10769:        /*   dval=dlval; */
                   10770:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10771:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10772:          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);
                   10773:          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);
                   10774:          return 1;
                   10775:        }
                   10776:        coqvar[iv][i]=dval; 
1.226     brouard  10777:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10778:       }
                   10779:       strcpy(line,stra);
                   10780:     }/* end loop nqv */
1.136     brouard  10781:     
1.223     brouard  10782:     /* Covariate values */
1.136     brouard  10783:     for (j=ncovcol;j>=1;j--){
                   10784:       cutv(stra, strb,line,' '); 
1.223     brouard  10785:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10786:        lval=-1;
1.136     brouard  10787:       }else{
1.225     brouard  10788:        errno=0;
                   10789:        lval=strtol(strb,&endptr,10); 
                   10790:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10791:          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);
                   10792:          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);
                   10793:          return 1;
                   10794:        }
1.136     brouard  10795:       }
                   10796:       if(lval <-1 || lval >1){
1.225     brouard  10797:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10798:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10799:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10800:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10801:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10802:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10803:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10804:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10805:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10806:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10807:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10808:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10809:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10810:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10811:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10812:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10813:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10814:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10815:        return 1;
1.136     brouard  10816:       }
                   10817:       covar[j][i]=(double)(lval);
                   10818:       strcpy(line,stra);
                   10819:     }  
                   10820:     lstra=strlen(stra);
1.225     brouard  10821:     
1.136     brouard  10822:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10823:       stratrunc = &(stra[lstra-9]);
                   10824:       num[i]=atol(stratrunc);
                   10825:     }
                   10826:     else
                   10827:       num[i]=atol(stra);
                   10828:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10829:       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;}*/
                   10830:     
                   10831:     i=i+1;
                   10832:   } /* End loop reading  data */
1.225     brouard  10833:   
1.136     brouard  10834:   *imax=i-1; /* Number of individuals */
                   10835:   fclose(fic);
1.225     brouard  10836:   
1.136     brouard  10837:   return (0);
1.164     brouard  10838:   /* endread: */
1.225     brouard  10839:   printf("Exiting readdata: ");
                   10840:   fclose(fic);
                   10841:   return (1);
1.223     brouard  10842: }
1.126     brouard  10843: 
1.234     brouard  10844: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10845:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10846:   while (*p2 == ' ')
1.234     brouard  10847:     p2++; 
                   10848:   /* while ((*p1++ = *p2++) !=0) */
                   10849:   /*   ; */
                   10850:   /* do */
                   10851:   /*   while (*p2 == ' ') */
                   10852:   /*     p2++; */
                   10853:   /* while (*p1++ == *p2++); */
                   10854:   *stri=p2; 
1.145     brouard  10855: }
                   10856: 
1.330     brouard  10857: int decoderesult( char resultline[], int nres)
1.230     brouard  10858: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10859: {
1.235     brouard  10860:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10861:   char resultsav[MAXLINE];
1.330     brouard  10862:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10863:   /* int modelresult[MAXLINE]; */
1.230     brouard  10864:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10865: 
1.234     brouard  10866:   removefirstspace(&resultline);
1.332     brouard  10867:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10868: 
1.332     brouard  10869:   strcpy(resultsav,resultline);
1.342     brouard  10870:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10871:   if (strlen(resultsav) >1){
1.334     brouard  10872:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10873:   }
1.253     brouard  10874:   if(j == 0){ /* Resultline but no = */
                   10875:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10876:     return (0);
                   10877:   }
1.234     brouard  10878:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10879:     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);
                   10880:     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  10881:     /* return 1;*/
1.234     brouard  10882:   }
1.334     brouard  10883:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10884:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10885:       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  10886:       /* 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  10887:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10888:       /* If a blank, then strc="V4=" and strd='\0' */
                   10889:       if(strc[0]=='\0'){
                   10890:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10891:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10892:        return 1;
                   10893:       }
1.234     brouard  10894:     }else
                   10895:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10896:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10897:     
1.230     brouard  10898:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10899:     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  10900:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10901:     /* cptcovsel++;     */
                   10902:     if (nbocc(stra,'=') >0)
                   10903:       strcpy(resultsav,stra); /* and analyzes it */
                   10904:   }
1.235     brouard  10905:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10906:   /* 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  10907:   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  10908:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10909:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10910:       match=0;
1.318     brouard  10911:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10912:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10913:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10914:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10915:          break;
                   10916:        }
                   10917:       }
                   10918:       if(match == 0){
1.338     brouard  10919:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10920:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s\n",Tvar[k1], resultline, model);
1.310     brouard  10921:        return 1;
1.234     brouard  10922:       }
1.332     brouard  10923:     }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*/
                   10924:       /* We feed resultmodel[k1]=k2; */
                   10925:       match=0;
                   10926:       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 */
                   10927:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10928:          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  10929:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10930:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10931:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10932:          break;
                   10933:        }
                   10934:       }
                   10935:       if(match == 0){
1.338     brouard  10936:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
                   10937:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10938:       return 1;
                   10939:       }
                   10940:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10941:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10942:       match=0;
1.342     brouard  10943:       /* 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]); */
1.332     brouard  10944:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10945:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10946:          /* modelresult[k2]=k1; */
1.342     brouard  10947:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10948:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10949:        }
                   10950:       }
                   10951:       if(match == 0){
1.338     brouard  10952:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10953:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10954:        return 1;
                   10955:       }
                   10956:       match=0;
                   10957:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10958:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10959:          /* modelresult[k2]=k1;*/
1.342     brouard  10960:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10961:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10962:          break;
                   10963:        }
                   10964:       }
                   10965:       if(match == 0){
1.338     brouard  10966:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10967:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10968:        return 1;
                   10969:       }
                   10970:     }/* End of testing */
1.333     brouard  10971:   }/* End loop cptcovt */
1.235     brouard  10972:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10973:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10974:   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)
                   10975:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10976:     match=0;
1.318     brouard  10977:     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  10978:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10979:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10980:          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  10981:          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  10982:          ++match;
                   10983:        }
                   10984:       }
                   10985:     }
                   10986:     if(match == 0){
1.338     brouard  10987:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10988:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10989:       return 1;
1.234     brouard  10990:     }else if(match > 1){
1.338     brouard  10991:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10992:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10993:       return 1;
1.234     brouard  10994:     }
                   10995:   }
1.334     brouard  10996:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10997:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10998:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10999:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11000:   /* 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*/
                   11001:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11002:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11003:   /*    1 0 0 0 */
                   11004:   /*    2 1 0 0 */
                   11005:   /*    3 0 1 0 */ 
1.330     brouard  11006:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11007:   /*    5 0 0 1 */
1.330     brouard  11008:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11009:   /*    7 0 1 1 */
                   11010:   /*    8 1 1 1 */
1.237     brouard  11011:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11012:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11013:   /* V5*age V5 known which value for nres?  */
                   11014:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11015:   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.
                   11016:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11017:     /* k counting number of combination of single dummies in the equation model */
                   11018:     /* k4 counting single dummies in the equation model */
                   11019:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11020:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
1.334     brouard  11021:        /* 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  11022:       /* 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  11023:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11024:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11025:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11026:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11027:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11028:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11029:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11030:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11031:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11032:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11033:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11034:       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  11035:       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  11036:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11037:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11038:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11039:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11040:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11041:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11042:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11043:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11044:       /* 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  11045:       k4++;;
1.331     brouard  11046:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11047:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11048:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11049:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11050:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11051:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11052:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11053:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11054:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11055:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11056:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11057:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11058:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11059:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11060:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11061:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11062:       /* 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  11063:       k4q++;;
1.331     brouard  11064:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11065:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11066:       /* Wrong we want the value of variable name Tvar[k1] */
                   11067:       
                   11068:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11069:       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  11070:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11071:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11072:       /* 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  11073:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11074:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11075:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11076:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11077:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11078:       /* 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  11079:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11080:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11081:       /* 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  11082:     }else{
1.332     brouard  11083:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11084:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11085:     }
                   11086:   }
1.234     brouard  11087:   
1.334     brouard  11088:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11089:   return (0);
                   11090: }
1.235     brouard  11091: 
1.230     brouard  11092: int decodemodel( char model[], int lastobs)
                   11093:  /**< This routine decodes the model and returns:
1.224     brouard  11094:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11095:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11096:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11097:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11098:        * - cptcovage number of covariates with age*products =2
                   11099:        * - cptcovs number of simple covariates
1.339     brouard  11100:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11101:        * - 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
1.339     brouard  11102:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11103:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11104:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11105:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11106:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11107:        */
1.319     brouard  11108: /* 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  11109: {
1.238     brouard  11110:   int i, j, k, ks, v;
1.227     brouard  11111:   int  j1, k1, k2, k3, k4;
1.136     brouard  11112:   char modelsav[80];
1.145     brouard  11113:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11114:   char *strpt;
1.136     brouard  11115: 
1.145     brouard  11116:   /*removespace(model);*/
1.136     brouard  11117:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11118:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11119:     if (strstr(model,"AGE") !=0){
1.192     brouard  11120:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11121:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11122:       return 1;
                   11123:     }
1.141     brouard  11124:     if (strstr(model,"v") !=0){
1.338     brouard  11125:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11126:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11127:       return 1;
                   11128:     }
1.187     brouard  11129:     strcpy(modelsav,model); 
                   11130:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11131:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11132:       if(strpt != model){
1.338     brouard  11133:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11134:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11135:  corresponding column of parameters.\n",model);
1.338     brouard  11136:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11137:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11138:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11139:        return 1;
1.225     brouard  11140:       }
1.187     brouard  11141:       nagesqr=1;
                   11142:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11143:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11144:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11145:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11146:       else 
1.234     brouard  11147:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11148:     }else
                   11149:       nagesqr=0;
                   11150:     if (strlen(modelsav) >1){
                   11151:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11152:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11153:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11154:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11155:                     * cst, age and age*age 
                   11156:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11157:       /* including age products which are counted in cptcovage.
                   11158:        * but the covariates which are products must be treated 
                   11159:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11160:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11161:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11162:       
                   11163:       
1.187     brouard  11164:       /*   Design
                   11165:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11166:        *  <          ncovcol=8                >
                   11167:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11168:        *   k=  1    2      3       4     5       6      7        8
                   11169:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11170:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11171:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11172:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11173:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11174:        *  Tage[++cptcovage]=k
1.345     brouard  11175:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11176:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11177:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11178:        *  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
                   11179:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11180:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11181:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11182:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11183:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11184:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11185:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11186:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11187:        * p Tprod[1]@2={                         6, 5}
                   11188:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11189:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11190:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11191:        *How to reorganize? Tvars(orted)
1.187     brouard  11192:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11193:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11194:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11195:        * Struct []
                   11196:        */
1.225     brouard  11197:       
1.187     brouard  11198:       /* This loop fills the array Tvar from the string 'model'.*/
                   11199:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11200:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11201:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11202:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11203:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11204:       /*       k=1 Tvar[1]=2 (from V2) */
                   11205:       /*       k=5 Tvar[5] */
                   11206:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11207:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11208:       /*       } */
1.198     brouard  11209:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11210:       /*
                   11211:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11212:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11213:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11214:       }
1.187     brouard  11215:       cptcovage=0;
1.319     brouard  11216:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11217:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11218:                                         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" */
                   11219:        if (nbocc(modelsav,'+')==0)
                   11220:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11221:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11222:        /*scanf("%d",i);*/
1.319     brouard  11223:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11224:          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  11225:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11226:            /* covar is not filled and then is empty */
                   11227:            cptcovprod--;
                   11228:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11229:            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  11230:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11231:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11232:            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  11233:            /*printf("stre=%s ", stre);*/
                   11234:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11235:            cptcovprod--;
                   11236:            cutl(stre,strb,strc,'V');
                   11237:            Tvar[k]=atoi(stre);
                   11238:            Typevar[k]=1;  /* 1 for age product */
                   11239:            cptcovage++;
                   11240:            Tage[cptcovage]=k;
                   11241:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11242:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11243:            cptcovn++;
                   11244:            cptcovprodnoage++;k1++;
                   11245:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11246:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11247:                                                because this model-covariate is a construction we invent a new column
                   11248:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11249:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11250:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11251:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11252:            /* Please remark that the new variables are model dependent */
                   11253:            /* If we have 4 variable but the model uses only 3, like in
                   11254:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11255:             *  k=     1     2       3   4     5        6        7       8
                   11256:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11257:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11258:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11259:             */
1.339     brouard  11260:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11261:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11262:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11263:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11264:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11265:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11266:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11267:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11268:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11269:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11270:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11271:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11272:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11273:            if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
                   11274:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11275:              /* Computes the new covariate which is a product of
                   11276:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11277:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11278:              }
                   11279:            } /*End of FixedV */
1.234     brouard  11280:          } /* End age is not in the model */
                   11281:        } /* End if model includes a product */
1.319     brouard  11282:        else { /* not a product */
1.234     brouard  11283:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11284:          /*  scanf("%d",i);*/
                   11285:          cutl(strd,strc,strb,'V');
                   11286:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11287:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11288:          Tvar[k]=atoi(strd);
                   11289:          Typevar[k]=0;  /* 0 for simple covariates */
                   11290:        }
                   11291:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11292:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11293:                                  scanf("%d",i);*/
1.187     brouard  11294:       } /* end of loop + on total covariates */
                   11295:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11296:   } /* end if strlen(model == 0) */
1.136     brouard  11297:   
                   11298:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11299:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11300:   
1.136     brouard  11301:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11302:      printf("cptcovprod=%d ", cptcovprod);
                   11303:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11304:      scanf("%d ",i);*/
                   11305: 
                   11306: 
1.230     brouard  11307: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11308:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11309: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11310:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11311:    k =           1    2   3     4       5       6      7      8        9
                   11312:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11313:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11314:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11315:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11316:          Tmodelind[combination of covar]=k;
1.225     brouard  11317: */  
                   11318: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11319:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11320:   /* 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  11321:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11322:   printf("Model=1+age+%s\n\
1.227     brouard  11323: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11324: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11325: 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  11326:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11327: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11328: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11329: 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.342     brouard  11330:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11331:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343     brouard  11332:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt loop on k from model */
1.234     brouard  11333:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11334:       Fixed[k]= 0;
                   11335:       Dummy[k]= 0;
1.225     brouard  11336:       ncoveff++;
1.232     brouard  11337:       ncovf++;
1.234     brouard  11338:       nsd++;
                   11339:       modell[k].maintype= FTYPE;
                   11340:       TvarsD[nsd]=Tvar[k];
                   11341:       TvarsDind[nsd]=k;
1.330     brouard  11342:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11343:       TvarF[ncovf]=Tvar[k];
                   11344:       TvarFind[ncovf]=k;
                   11345:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11346:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11347:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11348:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol */
1.234     brouard  11349:       Fixed[k]= 0;
                   11350:       Dummy[k]= 0;
                   11351:       ncoveff++;
                   11352:       ncovf++;
                   11353:       modell[k].maintype= FTYPE;
                   11354:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11355:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11356:       TvarFind[ncovf]=k;
1.230     brouard  11357:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11358:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11359:     }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  11360:       Fixed[k]= 0;
                   11361:       Dummy[k]= 1;
1.230     brouard  11362:       nqfveff++;
1.234     brouard  11363:       modell[k].maintype= FTYPE;
                   11364:       modell[k].subtype= FQ;
                   11365:       nsq++;
1.334     brouard  11366:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11367:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11368:       ncovf++;
1.234     brouard  11369:       TvarF[ncovf]=Tvar[k];
                   11370:       TvarFind[ncovf]=k;
1.231     brouard  11371:       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  11372:       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  11373:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11374:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11375:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11376:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11377:       ncovvt++;
                   11378:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11379:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11380: 
1.227     brouard  11381:       Fixed[k]= 1;
                   11382:       Dummy[k]= 0;
1.225     brouard  11383:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11384:       modell[k].maintype= VTYPE;
                   11385:       modell[k].subtype= VD;
                   11386:       nsd++;
                   11387:       TvarsD[nsd]=Tvar[k];
                   11388:       TvarsDind[nsd]=k;
1.330     brouard  11389:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11390:       ncovv++; /* Only simple time varying variables */
                   11391:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11392:       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  11393:       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 */
                   11394:       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  11395:       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);
                   11396:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11397:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11398:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11399:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11400:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11401:       ncovvt++;
                   11402:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11403:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11404:       
1.234     brouard  11405:       Fixed[k]= 1;
                   11406:       Dummy[k]= 1;
                   11407:       nqtveff++;
                   11408:       modell[k].maintype= VTYPE;
                   11409:       modell[k].subtype= VQ;
                   11410:       ncovv++; /* Only simple time varying variables */
                   11411:       nsq++;
1.334     brouard  11412:       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) */
                   11413:       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  11414:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11415:       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  11416:       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 */
                   11417:       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  11418:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11419:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11420:       /* 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); */
                   11421:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11422:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11423:       ncova++;
                   11424:       TvarA[ncova]=Tvar[k];
                   11425:       TvarAind[ncova]=k;
1.231     brouard  11426:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11427:        Fixed[k]= 2;
                   11428:        Dummy[k]= 2;
                   11429:        modell[k].maintype= ATYPE;
                   11430:        modell[k].subtype= APFD;
                   11431:        /* ncoveff++; */
1.227     brouard  11432:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11433:        Fixed[k]= 2;
                   11434:        Dummy[k]= 3;
                   11435:        modell[k].maintype= ATYPE;
                   11436:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11437:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11438:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11439:        Fixed[k]= 3;
                   11440:        Dummy[k]= 2;
                   11441:        modell[k].maintype= ATYPE;
                   11442:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11443:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11444:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11445:        Fixed[k]= 3;
                   11446:        Dummy[k]= 3;
                   11447:        modell[k].maintype= ATYPE;
                   11448:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11449:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11450:       }
1.339     brouard  11451:     }else if (Typevar[k] == 2) {  /* product Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
                   11452:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11453:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11454:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11455:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
                   11456:       ncovvt++;
                   11457:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11458:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11459:       ncovvt++;
                   11460:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11461:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11462: 
                   11463: 
                   11464:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11465:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11466:          Fixed[k]= 1;
                   11467:          Dummy[k]= 0;
                   11468:          modell[k].maintype= FTYPE;
                   11469:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11470:          ncovf++; /* Fixed variables without age */
                   11471:          TvarF[ncovf]=Tvar[k];
                   11472:          TvarFind[ncovf]=k;
1.339     brouard  11473:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11474:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11475:          Dummy[k]= 1;
                   11476:          modell[k].maintype= FTYPE;
                   11477:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11478:          ncovf++; /* Varying variables without age */
                   11479:          TvarF[ncovf]=Tvar[k];
                   11480:          TvarFind[ncovf]=k;
1.339     brouard  11481:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11482:          Fixed[k]= 1;
                   11483:          Dummy[k]= 0;
                   11484:          modell[k].maintype= VTYPE;
                   11485:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11486:          ncovv++; /* Varying variables without age */
1.339     brouard  11487:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11488:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11489:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11490:          Fixed[k]= 1;
                   11491:          Dummy[k]= 1;
                   11492:          modell[k].maintype= VTYPE;
                   11493:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11494:          ncovv++; /* Varying variables without age */
                   11495:          TvarV[ncovv]=Tvar[k];
                   11496:          TvarVind[ncovv]=k;
                   11497:        }
1.339     brouard  11498:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11499:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11500:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11501:          Dummy[k]= 1;
                   11502:          modell[k].maintype= FTYPE;
                   11503:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11504:          ncovf++; /* Fixed variables without age */
                   11505:          TvarF[ncovf]=Tvar[k];
                   11506:          TvarFind[ncovf]=k;
1.339     brouard  11507:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11508:          Fixed[k]= 1;
                   11509:          Dummy[k]= 1;
                   11510:          modell[k].maintype= VTYPE;
                   11511:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11512:          ncovv++; /* Varying variables without age */
                   11513:          TvarV[ncovv]=Tvar[k];
                   11514:          TvarVind[ncovv]=k;
1.339     brouard  11515:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11516:          Fixed[k]= 1;
                   11517:          Dummy[k]= 1;
                   11518:          modell[k].maintype= VTYPE;
                   11519:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11520:          ncovv++; /* Varying variables without age */
                   11521:          TvarV[ncovv]=Tvar[k];
                   11522:          TvarVind[ncovv]=k;
                   11523:          ncovv++; /* Varying variables without age */
                   11524:          TvarV[ncovv]=Tvar[k];
                   11525:          TvarVind[ncovv]=k;
                   11526:        }
1.339     brouard  11527:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11528:        if(Tvard[k1][2] <=ncovcol){
                   11529:          Fixed[k]= 1;
                   11530:          Dummy[k]= 1;
                   11531:          modell[k].maintype= VTYPE;
                   11532:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11533:          ncovv++; /* Varying variables without age */
                   11534:          TvarV[ncovv]=Tvar[k];
                   11535:          TvarVind[ncovv]=k;
                   11536:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11537:          Fixed[k]= 1;
                   11538:          Dummy[k]= 1;
                   11539:          modell[k].maintype= VTYPE;
                   11540:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11541:          ncovv++; /* Varying variables without age */
                   11542:          TvarV[ncovv]=Tvar[k];
                   11543:          TvarVind[ncovv]=k;
                   11544:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11545:          Fixed[k]= 1;
                   11546:          Dummy[k]= 0;
                   11547:          modell[k].maintype= VTYPE;
                   11548:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11549:          ncovv++; /* Varying variables without age */
                   11550:          TvarV[ncovv]=Tvar[k];
                   11551:          TvarVind[ncovv]=k;
                   11552:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11553:          Fixed[k]= 1;
                   11554:          Dummy[k]= 1;
                   11555:          modell[k].maintype= VTYPE;
                   11556:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11557:          ncovv++; /* Varying variables without age */
                   11558:          TvarV[ncovv]=Tvar[k];
                   11559:          TvarVind[ncovv]=k;
                   11560:        }
1.339     brouard  11561:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11562:        if(Tvard[k1][2] <=ncovcol){
                   11563:          Fixed[k]= 1;
                   11564:          Dummy[k]= 1;
                   11565:          modell[k].maintype= VTYPE;
                   11566:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11567:          ncovv++; /* Varying variables without age */
                   11568:          TvarV[ncovv]=Tvar[k];
                   11569:          TvarVind[ncovv]=k;
                   11570:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11571:          Fixed[k]= 1;
                   11572:          Dummy[k]= 1;
                   11573:          modell[k].maintype= VTYPE;
                   11574:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11575:          ncovv++; /* Varying variables without age */
                   11576:          TvarV[ncovv]=Tvar[k];
                   11577:          TvarVind[ncovv]=k;
                   11578:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11579:          Fixed[k]= 1;
                   11580:          Dummy[k]= 1;
                   11581:          modell[k].maintype= VTYPE;
                   11582:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11583:          ncovv++; /* Varying variables without age */
                   11584:          TvarV[ncovv]=Tvar[k];
                   11585:          TvarVind[ncovv]=k;
                   11586:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11587:          Fixed[k]= 1;
                   11588:          Dummy[k]= 1;
                   11589:          modell[k].maintype= VTYPE;
                   11590:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11591:          ncovv++; /* Varying variables without age */
                   11592:          TvarV[ncovv]=Tvar[k];
                   11593:          TvarVind[ncovv]=k;
                   11594:        }
1.227     brouard  11595:       }else{
1.240     brouard  11596:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11597:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11598:       } /*end k1*/
1.225     brouard  11599:     }else{
1.226     brouard  11600:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11601:       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  11602:     }
1.342     brouard  11603:     /* 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]); */
                   11604:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11605:     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]);
                   11606:   }
                   11607:   /* Searching for doublons in the model */
                   11608:   for(k1=1; k1<= cptcovt;k1++){
                   11609:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11610:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11611:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11612:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11613:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11614:            printf("Error duplication in the model=1+age+%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]);
                   11615:            fprintf(ficlog,"Error duplication in the model=1+age+%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  11616:            return(1);
                   11617:          }
                   11618:        }else if (Typevar[k1] ==2){
                   11619:          k3=Tposprod[k1];
                   11620:          k4=Tposprod[k2];
                   11621:          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])) ){
1.338     brouard  11622:            printf("Error duplication in the model=1+age+%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]]);
                   11623:            fprintf(ficlog,"Error duplication in the model=1+age+%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);
1.234     brouard  11624:            return(1);
                   11625:          }
                   11626:        }
1.227     brouard  11627:       }
                   11628:     }
1.225     brouard  11629:   }
                   11630:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11631:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11632:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11633:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11634:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11635:   /*endread:*/
1.225     brouard  11636:   printf("Exiting decodemodel: ");
                   11637:   return (1);
1.136     brouard  11638: }
                   11639: 
1.169     brouard  11640: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11641: {/* Check ages at death */
1.136     brouard  11642:   int i, m;
1.218     brouard  11643:   int firstone=0;
                   11644:   
1.136     brouard  11645:   for (i=1; i<=imx; i++) {
                   11646:     for(m=2; (m<= maxwav); m++) {
                   11647:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11648:        anint[m][i]=9999;
1.216     brouard  11649:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11650:          s[m][i]=-1;
1.136     brouard  11651:       }
                   11652:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11653:        *nberr = *nberr + 1;
1.218     brouard  11654:        if(firstone == 0){
                   11655:          firstone=1;
1.260     brouard  11656:        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  11657:        }
1.262     brouard  11658:        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  11659:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11660:       }
                   11661:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11662:        (*nberr)++;
1.259     brouard  11663:        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  11664:        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  11665:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11666:       }
                   11667:     }
                   11668:   }
                   11669: 
                   11670:   for (i=1; i<=imx; i++)  {
                   11671:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11672:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11673:       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  11674:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11675:          if(agedc[i]>0){
                   11676:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11677:              agev[m][i]=agedc[i];
1.214     brouard  11678:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11679:            }else {
1.136     brouard  11680:              if ((int)andc[i]!=9999){
                   11681:                nbwarn++;
                   11682:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11683:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11684:                agev[m][i]=-1;
                   11685:              }
                   11686:            }
1.169     brouard  11687:          } /* agedc > 0 */
1.214     brouard  11688:        } /* end if */
1.136     brouard  11689:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11690:                                 years but with the precision of a month */
                   11691:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11692:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11693:            agev[m][i]=1;
                   11694:          else if(agev[m][i] < *agemin){ 
                   11695:            *agemin=agev[m][i];
                   11696:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11697:          }
                   11698:          else if(agev[m][i] >*agemax){
                   11699:            *agemax=agev[m][i];
1.156     brouard  11700:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11701:          }
                   11702:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11703:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11704:        } /* en if 9*/
1.136     brouard  11705:        else { /* =9 */
1.214     brouard  11706:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11707:          agev[m][i]=1;
                   11708:          s[m][i]=-1;
                   11709:        }
                   11710:       }
1.214     brouard  11711:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11712:        agev[m][i]=1;
1.214     brouard  11713:       else{
                   11714:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11715:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11716:        agev[m][i]=0;
                   11717:       }
                   11718:     } /* End for lastpass */
                   11719:   }
1.136     brouard  11720:     
                   11721:   for (i=1; i<=imx; i++)  {
                   11722:     for(m=firstpass; (m<=lastpass); m++){
                   11723:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11724:        (*nberr)++;
1.136     brouard  11725:        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);     
                   11726:        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);     
                   11727:        return 1;
                   11728:       }
                   11729:     }
                   11730:   }
                   11731: 
                   11732:   /*for (i=1; i<=imx; i++){
                   11733:   for (m=firstpass; (m<lastpass); m++){
                   11734:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11735: }
                   11736: 
                   11737: }*/
                   11738: 
                   11739: 
1.139     brouard  11740:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11741:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11742: 
                   11743:   return (0);
1.164     brouard  11744:  /* endread:*/
1.136     brouard  11745:     printf("Exiting calandcheckages: ");
                   11746:     return (1);
                   11747: }
                   11748: 
1.172     brouard  11749: #if defined(_MSC_VER)
                   11750: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11751: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11752: //#include "stdafx.h"
                   11753: //#include <stdio.h>
                   11754: //#include <tchar.h>
                   11755: //#include <windows.h>
                   11756: //#include <iostream>
                   11757: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11758: 
                   11759: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11760: 
                   11761: BOOL IsWow64()
                   11762: {
                   11763:        BOOL bIsWow64 = FALSE;
                   11764: 
                   11765:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11766:        //  (HANDLE, PBOOL);
                   11767: 
                   11768:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11769: 
                   11770:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11771:        const char funcName[] = "IsWow64Process";
                   11772:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11773:                GetProcAddress(module, funcName);
                   11774: 
                   11775:        if (NULL != fnIsWow64Process)
                   11776:        {
                   11777:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11778:                        &bIsWow64))
                   11779:                        //throw std::exception("Unknown error");
                   11780:                        printf("Unknown error\n");
                   11781:        }
                   11782:        return bIsWow64 != FALSE;
                   11783: }
                   11784: #endif
1.177     brouard  11785: 
1.191     brouard  11786: void syscompilerinfo(int logged)
1.292     brouard  11787: {
                   11788: #include <stdint.h>
                   11789: 
                   11790:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11791:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11792:    /* /GS /W3 /Gy
                   11793:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11794:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11795:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11796:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11797:    */ 
                   11798:    /* 64 bits */
1.185     brouard  11799:    /*
                   11800:      /GS /W3 /Gy
                   11801:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11802:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11803:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11804:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11805:    /* Optimization are useless and O3 is slower than O2 */
                   11806:    /*
                   11807:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11808:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11809:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11810:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11811:    */
1.186     brouard  11812:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11813:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11814:       /PDB:"visual studio
                   11815:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11816:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11817:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11818:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11819:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11820:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11821:       uiAccess='false'"
                   11822:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11823:       /NOLOGO /TLBID:1
                   11824:    */
1.292     brouard  11825: 
                   11826: 
1.177     brouard  11827: #if defined __INTEL_COMPILER
1.178     brouard  11828: #if defined(__GNUC__)
                   11829:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11830: #endif
1.177     brouard  11831: #elif defined(__GNUC__) 
1.179     brouard  11832: #ifndef  __APPLE__
1.174     brouard  11833: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11834: #endif
1.177     brouard  11835:    struct utsname sysInfo;
1.178     brouard  11836:    int cross = CROSS;
                   11837:    if (cross){
                   11838:           printf("Cross-");
1.191     brouard  11839:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11840:    }
1.174     brouard  11841: #endif
                   11842: 
1.191     brouard  11843:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11844: #if defined(__clang__)
1.191     brouard  11845:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11846: #endif
                   11847: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11848:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11849: #endif
                   11850: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11851:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11852: #endif
                   11853: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11854:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11855: #endif
                   11856: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11857:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11858: #endif
                   11859: #if defined(_MSC_VER)
1.191     brouard  11860:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11861: #endif
                   11862: #if defined(__PGI)
1.191     brouard  11863:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11864: #endif
                   11865: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11866:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11867: #endif
1.191     brouard  11868:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11869:    
1.167     brouard  11870: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11871: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11872:     // Windows (x64 and x86)
1.191     brouard  11873:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11874: #elif __unix__ // all unices, not all compilers
                   11875:     // Unix
1.191     brouard  11876:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11877: #elif __linux__
                   11878:     // linux
1.191     brouard  11879:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11880: #elif __APPLE__
1.174     brouard  11881:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11882:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11883: #endif
                   11884: 
                   11885: /*  __MINGW32__          */
                   11886: /*  __CYGWIN__  */
                   11887: /* __MINGW64__  */
                   11888: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11889: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11890: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11891: /* _WIN64  // Defined for applications for Win64. */
                   11892: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11893: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11894: 
1.167     brouard  11895: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11896:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11897: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11898:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11899: #else
1.191     brouard  11900:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11901: #endif
                   11902: 
1.169     brouard  11903: #if defined(__GNUC__)
                   11904: # if defined(__GNUC_PATCHLEVEL__)
                   11905: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11906:                             + __GNUC_MINOR__ * 100 \
                   11907:                             + __GNUC_PATCHLEVEL__)
                   11908: # else
                   11909: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11910:                             + __GNUC_MINOR__ * 100)
                   11911: # endif
1.174     brouard  11912:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11913:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11914: 
                   11915:    if (uname(&sysInfo) != -1) {
                   11916:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11917:         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  11918:    }
                   11919:    else
                   11920:       perror("uname() error");
1.179     brouard  11921:    //#ifndef __INTEL_COMPILER 
                   11922: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11923:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11924:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11925: #endif
1.169     brouard  11926: #endif
1.172     brouard  11927: 
1.286     brouard  11928:    //   void main ()
1.172     brouard  11929:    //   {
1.169     brouard  11930: #if defined(_MSC_VER)
1.174     brouard  11931:    if (IsWow64()){
1.191     brouard  11932:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11933:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11934:    }
                   11935:    else{
1.191     brouard  11936:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11937:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11938:    }
1.172     brouard  11939:    //     printf("\nPress Enter to continue...");
                   11940:    //     getchar();
                   11941:    //   }
                   11942: 
1.169     brouard  11943: #endif
                   11944:    
1.167     brouard  11945: 
1.219     brouard  11946: }
1.136     brouard  11947: 
1.219     brouard  11948: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11949:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11950:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11951:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11952:   /* double ftolpl = 1.e-10; */
1.180     brouard  11953:   double age, agebase, agelim;
1.203     brouard  11954:   double tot;
1.180     brouard  11955: 
1.202     brouard  11956:   strcpy(filerespl,"PL_");
                   11957:   strcat(filerespl,fileresu);
                   11958:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11959:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11960:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11961:   }
1.288     brouard  11962:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11963:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11964:   pstamp(ficrespl);
1.288     brouard  11965:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11966:   fprintf(ficrespl,"#Age ");
                   11967:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11968:   fprintf(ficrespl,"\n");
1.180     brouard  11969:   
1.219     brouard  11970:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11971: 
1.219     brouard  11972:   agebase=ageminpar;
                   11973:   agelim=agemaxpar;
1.180     brouard  11974: 
1.227     brouard  11975:   /* i1=pow(2,ncoveff); */
1.234     brouard  11976:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11977:   if (cptcovn < 1){i1=1;}
1.180     brouard  11978: 
1.337     brouard  11979:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11980:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11981:       k=TKresult[nres];
1.338     brouard  11982:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11983:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11984:       /*       continue; */
1.235     brouard  11985: 
1.238     brouard  11986:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11987:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11988:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11989:       /* k=k+1; */
                   11990:       /* to clean */
1.332     brouard  11991:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11992:       fprintf(ficrespl,"#******");
                   11993:       printf("#******");
                   11994:       fprintf(ficlog,"#******");
1.337     brouard  11995:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
1.332     brouard  11996:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11997:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11998:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11999:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12000:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12001:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12002:       }
                   12003:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12004:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12005:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12006:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12007:       /* } */
1.238     brouard  12008:       fprintf(ficrespl,"******\n");
                   12009:       printf("******\n");
                   12010:       fprintf(ficlog,"******\n");
                   12011:       if(invalidvarcomb[k]){
                   12012:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12013:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12014:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12015:        continue;
                   12016:       }
1.219     brouard  12017: 
1.238     brouard  12018:       fprintf(ficrespl,"#Age ");
1.337     brouard  12019:       /* for(j=1;j<=cptcoveff;j++) { */
                   12020:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12021:       /* } */
                   12022:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12023:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12024:       }
                   12025:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12026:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12027:     
1.238     brouard  12028:       for (age=agebase; age<=agelim; age++){
                   12029:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12030:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12031:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12032:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12033:        /* for(j=1;j<=cptcoveff;j++) */
                   12034:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12035:        for(j=1;j<=cptcovs;j++)
                   12036:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12037:        tot=0.;
                   12038:        for(i=1; i<=nlstate;i++){
                   12039:          tot +=  prlim[i][i];
                   12040:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12041:        }
                   12042:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12043:       } /* Age */
                   12044:       /* was end of cptcod */
1.337     brouard  12045:     } /* nres */
                   12046:   /* } /\* for each combination *\/ */
1.219     brouard  12047:   return 0;
1.180     brouard  12048: }
                   12049: 
1.218     brouard  12050: 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  12051:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12052:        
                   12053:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12054:    * at any age between ageminpar and agemaxpar
                   12055:         */
1.235     brouard  12056:   int i, j, k, i1, nres=0 ;
1.217     brouard  12057:   /* double ftolpl = 1.e-10; */
                   12058:   double age, agebase, agelim;
                   12059:   double tot;
1.218     brouard  12060:   /* double ***mobaverage; */
                   12061:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12062: 
                   12063:   strcpy(fileresplb,"PLB_");
                   12064:   strcat(fileresplb,fileresu);
                   12065:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12066:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12067:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12068:   }
1.288     brouard  12069:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12070:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12071:   pstamp(ficresplb);
1.288     brouard  12072:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12073:   fprintf(ficresplb,"#Age ");
                   12074:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12075:   fprintf(ficresplb,"\n");
                   12076:   
1.218     brouard  12077:   
                   12078:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12079:   
                   12080:   agebase=ageminpar;
                   12081:   agelim=agemaxpar;
                   12082:   
                   12083:   
1.227     brouard  12084:   i1=pow(2,cptcoveff);
1.218     brouard  12085:   if (cptcovn < 1){i1=1;}
1.227     brouard  12086:   
1.238     brouard  12087:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12088:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12089:       k=TKresult[nres];
                   12090:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12091:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12092:      /*        continue; */
                   12093:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12094:       fprintf(ficresplb,"#******");
                   12095:       printf("#******");
                   12096:       fprintf(ficlog,"#******");
1.338     brouard  12097:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
                   12098:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12099:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12100:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12101:       }
1.338     brouard  12102:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12103:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12104:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12105:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12106:       /* } */
                   12107:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12108:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12109:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12110:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12111:       /* } */
1.238     brouard  12112:       fprintf(ficresplb,"******\n");
                   12113:       printf("******\n");
                   12114:       fprintf(ficlog,"******\n");
                   12115:       if(invalidvarcomb[k]){
                   12116:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12117:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12118:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12119:        continue;
                   12120:       }
1.218     brouard  12121:     
1.238     brouard  12122:       fprintf(ficresplb,"#Age ");
1.338     brouard  12123:       for(j=1;j<=cptcovs;j++) {
                   12124:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12125:       }
                   12126:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12127:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12128:     
                   12129:     
1.238     brouard  12130:       for (age=agebase; age<=agelim; age++){
                   12131:        /* for (age=agebase; age<=agebase; age++){ */
                   12132:        if(mobilavproj > 0){
                   12133:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12134:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12135:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12136:        }else if (mobilavproj == 0){
                   12137:          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);
                   12138:          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);
                   12139:          exit(1);
                   12140:        }else{
                   12141:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12142:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12143:          /* printf("TOTOT\n"); */
                   12144:           /* exit(1); */
1.238     brouard  12145:        }
                   12146:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12147:        for(j=1;j<=cptcovs;j++)
                   12148:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12149:        tot=0.;
                   12150:        for(i=1; i<=nlstate;i++){
                   12151:          tot +=  bprlim[i][i];
                   12152:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12153:        }
                   12154:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12155:       } /* Age */
                   12156:       /* was end of cptcod */
1.255     brouard  12157:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12158:     /* } /\* end of any combination *\/ */
1.238     brouard  12159:   } /* end of nres */  
1.218     brouard  12160:   /* hBijx(p, bage, fage); */
                   12161:   /* fclose(ficrespijb); */
                   12162:   
                   12163:   return 0;
1.217     brouard  12164: }
1.218     brouard  12165:  
1.180     brouard  12166: int hPijx(double *p, int bage, int fage){
                   12167:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12168:   /* to be optimized with precov */
1.180     brouard  12169:   int stepsize;
                   12170:   int agelim;
                   12171:   int hstepm;
                   12172:   int nhstepm;
1.235     brouard  12173:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12174: 
                   12175:   double agedeb;
                   12176:   double ***p3mat;
                   12177: 
1.337     brouard  12178:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12179:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12180:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12181:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12182:   }
                   12183:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12184:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12185:   
                   12186:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12187:   /*if (stepm<=24) stepsize=2;*/
                   12188:   
                   12189:   agelim=AGESUP;
                   12190:   hstepm=stepsize*YEARM; /* Every year of age */
                   12191:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12192:   
                   12193:   /* hstepm=1;   aff par mois*/
                   12194:   pstamp(ficrespij);
                   12195:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12196:   i1= pow(2,cptcoveff);
                   12197:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12198:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12199:   /*   k=k+1;  */
                   12200:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12201:     k=TKresult[nres];
1.338     brouard  12202:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12203:     /* for(k=1; k<=i1;k++){ */
                   12204:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12205:     /*         continue; */
                   12206:     fprintf(ficrespij,"\n#****** ");
                   12207:     for(j=1;j<=cptcovs;j++){
                   12208:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12209:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12210:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12211:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12212:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12213:     }
                   12214:     fprintf(ficrespij,"******\n");
                   12215:     
                   12216:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12217:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12218:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12219:       
                   12220:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12221:       
                   12222:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12223:       oldm=oldms;savm=savms;
                   12224:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12225:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12226:       for(i=1; i<=nlstate;i++)
                   12227:        for(j=1; j<=nlstate+ndeath;j++)
                   12228:          fprintf(ficrespij," %1d-%1d",i,j);
                   12229:       fprintf(ficrespij,"\n");
                   12230:       for (h=0; h<=nhstepm; h++){
                   12231:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12232:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12233:        for(i=1; i<=nlstate;i++)
                   12234:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12235:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12236:        fprintf(ficrespij,"\n");
                   12237:       }
1.337     brouard  12238:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12239:       fprintf(ficrespij,"\n");
1.180     brouard  12240:     }
1.337     brouard  12241:   }
                   12242:   /*}*/
                   12243:   return 0;
1.180     brouard  12244: }
1.218     brouard  12245:  
                   12246:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12247:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12248:     /* To be optimized with precov */
1.217     brouard  12249:   int stepsize;
1.218     brouard  12250:   /* int agelim; */
                   12251:        int ageminl;
1.217     brouard  12252:   int hstepm;
                   12253:   int nhstepm;
1.238     brouard  12254:   int h, i, i1, j, k, nres;
1.218     brouard  12255:        
1.217     brouard  12256:   double agedeb;
                   12257:   double ***p3mat;
1.218     brouard  12258:        
                   12259:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12260:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12261:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12262:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12263:   }
                   12264:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12265:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12266:   
                   12267:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12268:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12269:   
1.218     brouard  12270:   /* agelim=AGESUP; */
1.289     brouard  12271:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12272:   hstepm=stepsize*YEARM; /* Every year of age */
                   12273:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12274:   
                   12275:   /* hstepm=1;   aff par mois*/
                   12276:   pstamp(ficrespijb);
1.255     brouard  12277:   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  12278:   i1= pow(2,cptcoveff);
1.218     brouard  12279:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12280:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12281:   /*   k=k+1;  */
1.238     brouard  12282:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12283:     k=TKresult[nres];
1.338     brouard  12284:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12285:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12286:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12287:     /*         continue; */
                   12288:     fprintf(ficrespijb,"\n#****** ");
                   12289:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12290:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12291:       /* for(j=1;j<=cptcoveff;j++) */
                   12292:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12293:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12294:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12295:     }
                   12296:     fprintf(ficrespijb,"******\n");
                   12297:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12298:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12299:       continue;
                   12300:     }
                   12301:     
                   12302:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12303:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12304:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12305:       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 */
                   12306:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12307:       
                   12308:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12309:       
                   12310:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12311:       /* and memory limitations if stepm is small */
                   12312:       
                   12313:       /* oldm=oldms;savm=savms; */
                   12314:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12315:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12316:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12317:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12318:       for(i=1; i<=nlstate;i++)
                   12319:        for(j=1; j<=nlstate+ndeath;j++)
                   12320:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12321:       fprintf(ficrespijb,"\n");
                   12322:       for (h=0; h<=nhstepm; h++){
                   12323:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12324:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12325:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12326:        for(i=1; i<=nlstate;i++)
                   12327:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12328:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12329:        fprintf(ficrespijb,"\n");
1.337     brouard  12330:       }
                   12331:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12332:       fprintf(ficrespijb,"\n");
                   12333:     } /* end age deb */
                   12334:     /* } /\* end combination *\/ */
1.238     brouard  12335:   } /* end nres */
1.218     brouard  12336:   return 0;
                   12337:  } /*  hBijx */
1.217     brouard  12338: 
1.180     brouard  12339: 
1.136     brouard  12340: /***********************************************/
                   12341: /**************** Main Program *****************/
                   12342: /***********************************************/
                   12343: 
                   12344: int main(int argc, char *argv[])
                   12345: {
                   12346: #ifdef GSL
                   12347:   const gsl_multimin_fminimizer_type *T;
                   12348:   size_t iteri = 0, it;
                   12349:   int rval = GSL_CONTINUE;
                   12350:   int status = GSL_SUCCESS;
                   12351:   double ssval;
                   12352: #endif
                   12353:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12354:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12355:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12356:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12357:   int jj, ll, li, lj, lk;
1.136     brouard  12358:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12359:   int num_filled;
1.136     brouard  12360:   int itimes;
                   12361:   int NDIM=2;
                   12362:   int vpopbased=0;
1.235     brouard  12363:   int nres=0;
1.258     brouard  12364:   int endishere=0;
1.277     brouard  12365:   int noffset=0;
1.274     brouard  12366:   int ncurrv=0; /* Temporary variable */
                   12367:   
1.164     brouard  12368:   char ca[32], cb[32];
1.136     brouard  12369:   /*  FILE *fichtm; *//* Html File */
                   12370:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12371:   struct stat info;
1.191     brouard  12372:   double agedeb=0.;
1.194     brouard  12373: 
                   12374:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12375:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12376: 
1.165     brouard  12377:   double fret;
1.191     brouard  12378:   double dum=0.; /* Dummy variable */
1.136     brouard  12379:   double ***p3mat;
1.218     brouard  12380:   /* double ***mobaverage; */
1.319     brouard  12381:   double wald;
1.164     brouard  12382: 
                   12383:   char line[MAXLINE];
1.197     brouard  12384:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12385: 
1.234     brouard  12386:   char  modeltemp[MAXLINE];
1.332     brouard  12387:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12388:   
1.136     brouard  12389:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12390:   char *tok, *val; /* pathtot */
1.334     brouard  12391:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12392:   int c,  h , cpt, c2;
1.191     brouard  12393:   int jl=0;
                   12394:   int i1, j1, jk, stepsize=0;
1.194     brouard  12395:   int count=0;
                   12396: 
1.164     brouard  12397:   int *tab; 
1.136     brouard  12398:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12399:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12400:   /* double anprojf, mprojf, jprojf; */
                   12401:   /* double jintmean,mintmean,aintmean;   */
                   12402:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12403:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12404:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12405:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12406:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12407:   int mobilav=0,popforecast=0;
1.191     brouard  12408:   int hstepm=0, nhstepm=0;
1.136     brouard  12409:   int agemortsup;
                   12410:   float  sumlpop=0.;
                   12411:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12412:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12413: 
1.191     brouard  12414:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12415:   double ftolpl=FTOL;
                   12416:   double **prlim;
1.217     brouard  12417:   double **bprlim;
1.317     brouard  12418:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12419:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12420:   double ***paramstart; /* Matrix of starting parameter values */
                   12421:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12422:   double **matcov; /* Matrix of covariance */
1.203     brouard  12423:   double **hess; /* Hessian matrix */
1.136     brouard  12424:   double ***delti3; /* Scale */
                   12425:   double *delti; /* Scale */
                   12426:   double ***eij, ***vareij;
                   12427:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12428: 
1.136     brouard  12429:   double *epj, vepp;
1.164     brouard  12430: 
1.273     brouard  12431:   double dateprev1, dateprev2;
1.296     brouard  12432:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12433:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12434: 
1.217     brouard  12435: 
1.136     brouard  12436:   double **ximort;
1.145     brouard  12437:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12438:   int *dcwave;
                   12439: 
1.164     brouard  12440:   char z[1]="c";
1.136     brouard  12441: 
                   12442:   /*char  *strt;*/
                   12443:   char strtend[80];
1.126     brouard  12444: 
1.164     brouard  12445: 
1.126     brouard  12446: /*   setlocale (LC_ALL, ""); */
                   12447: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12448: /*   textdomain (PACKAGE); */
                   12449: /*   setlocale (LC_CTYPE, ""); */
                   12450: /*   setlocale (LC_MESSAGES, ""); */
                   12451: 
                   12452:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12453:   rstart_time = time(NULL);  
                   12454:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12455:   start_time = *localtime(&rstart_time);
1.126     brouard  12456:   curr_time=start_time;
1.157     brouard  12457:   /*tml = *localtime(&start_time.tm_sec);*/
                   12458:   /* strcpy(strstart,asctime(&tml)); */
                   12459:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12460: 
                   12461: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12462: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12463: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12464: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12465: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12466: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12467: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12468: /*   strt=asctime(&tmg); */
                   12469: /*   printf("Time(after) =%s",strstart);  */
                   12470: /*  (void) time (&time_value);
                   12471: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12472: *  tm = *localtime(&time_value);
                   12473: *  strstart=asctime(&tm);
                   12474: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12475: */
                   12476: 
                   12477:   nberr=0; /* Number of errors and warnings */
                   12478:   nbwarn=0;
1.184     brouard  12479: #ifdef WIN32
                   12480:   _getcwd(pathcd, size);
                   12481: #else
1.126     brouard  12482:   getcwd(pathcd, size);
1.184     brouard  12483: #endif
1.191     brouard  12484:   syscompilerinfo(0);
1.196     brouard  12485:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12486:   if(argc <=1){
                   12487:     printf("\nEnter the parameter file name: ");
1.205     brouard  12488:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12489:       printf("ERROR Empty parameter file name\n");
                   12490:       goto end;
                   12491:     }
1.126     brouard  12492:     i=strlen(pathr);
                   12493:     if(pathr[i-1]=='\n')
                   12494:       pathr[i-1]='\0';
1.156     brouard  12495:     i=strlen(pathr);
1.205     brouard  12496:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12497:       pathr[i-1]='\0';
1.205     brouard  12498:     }
                   12499:     i=strlen(pathr);
                   12500:     if( i==0 ){
                   12501:       printf("ERROR Empty parameter file name\n");
                   12502:       goto end;
                   12503:     }
                   12504:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12505:       printf("Pathr |%s|\n",pathr);
                   12506:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12507:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12508:       strcpy (pathtot, val);
                   12509:       if(pathr[0] == '\0') break; /* Dirty */
                   12510:     }
                   12511:   }
1.281     brouard  12512:   else if (argc<=2){
                   12513:     strcpy(pathtot,argv[1]);
                   12514:   }
1.126     brouard  12515:   else{
                   12516:     strcpy(pathtot,argv[1]);
1.281     brouard  12517:     strcpy(z,argv[2]);
                   12518:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12519:   }
                   12520:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12521:   /*cygwin_split_path(pathtot,path,optionfile);
                   12522:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12523:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12524: 
                   12525:   /* Split argv[0], imach program to get pathimach */
                   12526:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12527:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12528:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12529:  /*   strcpy(pathimach,argv[0]); */
                   12530:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12531:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12532:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12533: #ifdef WIN32
                   12534:   _chdir(path); /* Can be a relative path */
                   12535:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12536: #else
1.126     brouard  12537:   chdir(path); /* Can be a relative path */
1.184     brouard  12538:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12539: #endif
                   12540:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12541:   strcpy(command,"mkdir ");
                   12542:   strcat(command,optionfilefiname);
                   12543:   if((outcmd=system(command)) != 0){
1.169     brouard  12544:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12545:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12546:     /* fclose(ficlog); */
                   12547: /*     exit(1); */
                   12548:   }
                   12549: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12550: /*     perror("mkdir"); */
                   12551: /*   } */
                   12552: 
                   12553:   /*-------- arguments in the command line --------*/
                   12554: 
1.186     brouard  12555:   /* Main Log file */
1.126     brouard  12556:   strcat(filelog, optionfilefiname);
                   12557:   strcat(filelog,".log");    /* */
                   12558:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12559:     printf("Problem with logfile %s\n",filelog);
                   12560:     goto end;
                   12561:   }
                   12562:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12563:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12564:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12565:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12566:  path=%s \n\
                   12567:  optionfile=%s\n\
                   12568:  optionfilext=%s\n\
1.156     brouard  12569:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12570: 
1.197     brouard  12571:   syscompilerinfo(1);
1.167     brouard  12572: 
1.126     brouard  12573:   printf("Local time (at start):%s",strstart);
                   12574:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12575:   fflush(ficlog);
                   12576: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12577: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12578: 
                   12579:   /* */
                   12580:   strcpy(fileres,"r");
                   12581:   strcat(fileres, optionfilefiname);
1.201     brouard  12582:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12583:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12584:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12585: 
1.186     brouard  12586:   /* Main ---------arguments file --------*/
1.126     brouard  12587: 
                   12588:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12589:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12590:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12591:     fflush(ficlog);
1.149     brouard  12592:     /* goto end; */
                   12593:     exit(70); 
1.126     brouard  12594:   }
                   12595: 
                   12596:   strcpy(filereso,"o");
1.201     brouard  12597:   strcat(filereso,fileresu);
1.126     brouard  12598:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12599:     printf("Problem with Output resultfile: %s\n", filereso);
                   12600:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12601:     fflush(ficlog);
                   12602:     goto end;
                   12603:   }
1.278     brouard  12604:       /*-------- Rewriting parameter file ----------*/
                   12605:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12606:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12607:   strcat(rfileres,".");    /* */
                   12608:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12609:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12610:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12611:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12612:     fflush(ficlog);
                   12613:     goto end;
                   12614:   }
                   12615:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12616: 
1.278     brouard  12617:                                      
1.126     brouard  12618:   /* Reads comments: lines beginning with '#' */
                   12619:   numlinepar=0;
1.277     brouard  12620:   /* Is it a BOM UTF-8 Windows file? */
                   12621:   /* First parameter line */
1.197     brouard  12622:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12623:     noffset=0;
                   12624:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12625:     {
                   12626:       noffset=noffset+3;
                   12627:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12628:     }
1.302     brouard  12629: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12630:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12631:     {
                   12632:       noffset=noffset+2;
                   12633:       printf("# File is an UTF16BE BOM file\n");
                   12634:     }
                   12635:     else if( line[0] == 0 && line[1] == 0)
                   12636:     {
                   12637:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12638:        noffset=noffset+4;
                   12639:        printf("# File is an UTF16BE BOM file\n");
                   12640:       }
                   12641:     } else{
                   12642:       ;/*printf(" Not a BOM file\n");*/
                   12643:     }
                   12644:   
1.197     brouard  12645:     /* If line starts with a # it is a comment */
1.277     brouard  12646:     if (line[noffset] == '#') {
1.197     brouard  12647:       numlinepar++;
                   12648:       fputs(line,stdout);
                   12649:       fputs(line,ficparo);
1.278     brouard  12650:       fputs(line,ficres);
1.197     brouard  12651:       fputs(line,ficlog);
                   12652:       continue;
                   12653:     }else
                   12654:       break;
                   12655:   }
                   12656:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12657:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12658:     if (num_filled != 5) {
                   12659:       printf("Should be 5 parameters\n");
1.283     brouard  12660:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12661:     }
1.126     brouard  12662:     numlinepar++;
1.197     brouard  12663:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12664:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12665:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12666:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12667:   }
                   12668:   /* Second parameter line */
                   12669:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12670:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12671:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12672:     if (line[0] == '#') {
                   12673:       numlinepar++;
1.283     brouard  12674:       printf("%s",line);
                   12675:       fprintf(ficres,"%s",line);
                   12676:       fprintf(ficparo,"%s",line);
                   12677:       fprintf(ficlog,"%s",line);
1.197     brouard  12678:       continue;
                   12679:     }else
                   12680:       break;
                   12681:   }
1.223     brouard  12682:   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", \
                   12683:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12684:     if (num_filled != 11) {
                   12685:       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  12686:       printf("but line=%s\n",line);
1.283     brouard  12687:       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");
                   12688:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12689:     }
1.286     brouard  12690:     if( lastpass > maxwav){
                   12691:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12692:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12693:       fflush(ficlog);
                   12694:       goto end;
                   12695:     }
                   12696:       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  12697:     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  12698:     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  12699:     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  12700:   }
1.203     brouard  12701:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12702:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12703:   /* Third parameter line */
                   12704:   while(fgets(line, MAXLINE, ficpar)) {
                   12705:     /* If line starts with a # it is a comment */
                   12706:     if (line[0] == '#') {
                   12707:       numlinepar++;
1.283     brouard  12708:       printf("%s",line);
                   12709:       fprintf(ficres,"%s",line);
                   12710:       fprintf(ficparo,"%s",line);
                   12711:       fprintf(ficlog,"%s",line);
1.197     brouard  12712:       continue;
                   12713:     }else
                   12714:       break;
                   12715:   }
1.201     brouard  12716:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12717:     if (num_filled != 1){
1.302     brouard  12718:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12719:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12720:       model[0]='\0';
                   12721:       goto end;
                   12722:     }
                   12723:     else{
                   12724:       if (model[0]=='+'){
                   12725:        for(i=1; i<=strlen(model);i++)
                   12726:          modeltemp[i-1]=model[i];
1.201     brouard  12727:        strcpy(model,modeltemp); 
1.197     brouard  12728:       }
                   12729:     }
1.338     brouard  12730:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12731:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12732:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12733:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12734:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12735:   }
                   12736:   /* 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); */
                   12737:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12738:   /* 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  12739:   /* 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); */
                   12740:   /* 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  12741:   fflush(ficlog);
1.190     brouard  12742:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12743:   if(model[0]=='#'){
1.279     brouard  12744:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12745:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12746:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12747:     if(mle != -1){
1.279     brouard  12748:       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  12749:       exit(1);
                   12750:     }
                   12751:   }
1.126     brouard  12752:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12753:     ungetc(c,ficpar);
                   12754:     fgets(line, MAXLINE, ficpar);
                   12755:     numlinepar++;
1.195     brouard  12756:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12757:       z[0]=line[1];
1.342     brouard  12758:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  12759:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12760:     }
                   12761:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12762:     fputs(line, stdout);
                   12763:     //puts(line);
1.126     brouard  12764:     fputs(line,ficparo);
                   12765:     fputs(line,ficlog);
                   12766:   }
                   12767:   ungetc(c,ficpar);
                   12768: 
                   12769:    
1.290     brouard  12770:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12771:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12772:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12773:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12774:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12775:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12776:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12777:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12778:   */
                   12779:   if (strlen(model)>1) 
1.187     brouard  12780:     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  12781:   else
1.187     brouard  12782:     ncovmodel=2; /* Constant and age */
1.133     brouard  12783:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12784:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12785:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12786:     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);
                   12787:     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);
                   12788:     fflush(stdout);
                   12789:     fclose (ficlog);
                   12790:     goto end;
                   12791:   }
1.126     brouard  12792:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12793:   delti=delti3[1][1];
                   12794:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12795:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12796: /* We could also provide initial parameters values giving by simple logistic regression 
                   12797:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12798:       /* for(i=1;i<nlstate;i++){ */
                   12799:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12800:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12801:       /* } */
1.126     brouard  12802:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12803:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12804:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12805:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12806:     fclose (ficparo);
                   12807:     fclose (ficlog);
                   12808:     goto end;
                   12809:     exit(0);
1.220     brouard  12810:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12811:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12812:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12813:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12814:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12815:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12816:     hess=matrix(1,npar,1,npar);
1.220     brouard  12817:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12818:     /* Read guessed parameters */
1.126     brouard  12819:     /* Reads comments: lines beginning with '#' */
                   12820:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12821:       ungetc(c,ficpar);
                   12822:       fgets(line, MAXLINE, ficpar);
                   12823:       numlinepar++;
1.141     brouard  12824:       fputs(line,stdout);
1.126     brouard  12825:       fputs(line,ficparo);
                   12826:       fputs(line,ficlog);
                   12827:     }
                   12828:     ungetc(c,ficpar);
                   12829:     
                   12830:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12831:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12832:     for(i=1; i <=nlstate; i++){
1.234     brouard  12833:       j=0;
1.126     brouard  12834:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12835:        if(jj==i) continue;
                   12836:        j++;
1.292     brouard  12837:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12838:          ungetc(c,ficpar);
                   12839:          fgets(line, MAXLINE, ficpar);
                   12840:          numlinepar++;
                   12841:          fputs(line,stdout);
                   12842:          fputs(line,ficparo);
                   12843:          fputs(line,ficlog);
                   12844:        }
                   12845:        ungetc(c,ficpar);
1.234     brouard  12846:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12847:        if ((i1 != i) || (j1 != jj)){
                   12848:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12849: It might be a problem of design; if ncovcol and the model are correct\n \
                   12850: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12851:          exit(1);
                   12852:        }
                   12853:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12854:        if(mle==1)
                   12855:          printf("%1d%1d",i,jj);
                   12856:        fprintf(ficlog,"%1d%1d",i,jj);
                   12857:        for(k=1; k<=ncovmodel;k++){
                   12858:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12859:          if(mle==1){
                   12860:            printf(" %lf",param[i][j][k]);
                   12861:            fprintf(ficlog," %lf",param[i][j][k]);
                   12862:          }
                   12863:          else
                   12864:            fprintf(ficlog," %lf",param[i][j][k]);
                   12865:          fprintf(ficparo," %lf",param[i][j][k]);
                   12866:        }
                   12867:        fscanf(ficpar,"\n");
                   12868:        numlinepar++;
                   12869:        if(mle==1)
                   12870:          printf("\n");
                   12871:        fprintf(ficlog,"\n");
                   12872:        fprintf(ficparo,"\n");
1.126     brouard  12873:       }
                   12874:     }  
                   12875:     fflush(ficlog);
1.234     brouard  12876:     
1.251     brouard  12877:     /* Reads parameters values */
1.126     brouard  12878:     p=param[1][1];
1.251     brouard  12879:     pstart=paramstart[1][1];
1.126     brouard  12880:     
                   12881:     /* Reads comments: lines beginning with '#' */
                   12882:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12883:       ungetc(c,ficpar);
                   12884:       fgets(line, MAXLINE, ficpar);
                   12885:       numlinepar++;
1.141     brouard  12886:       fputs(line,stdout);
1.126     brouard  12887:       fputs(line,ficparo);
                   12888:       fputs(line,ficlog);
                   12889:     }
                   12890:     ungetc(c,ficpar);
                   12891: 
                   12892:     for(i=1; i <=nlstate; i++){
                   12893:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12894:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12895:        if ( (i1-i) * (j1-j) != 0){
                   12896:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12897:          exit(1);
                   12898:        }
                   12899:        printf("%1d%1d",i,j);
                   12900:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12901:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12902:        for(k=1; k<=ncovmodel;k++){
                   12903:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12904:          printf(" %le",delti3[i][j][k]);
                   12905:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12906:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12907:        }
                   12908:        fscanf(ficpar,"\n");
                   12909:        numlinepar++;
                   12910:        printf("\n");
                   12911:        fprintf(ficparo,"\n");
                   12912:        fprintf(ficlog,"\n");
1.126     brouard  12913:       }
                   12914:     }
                   12915:     fflush(ficlog);
1.234     brouard  12916:     
1.145     brouard  12917:     /* Reads covariance matrix */
1.126     brouard  12918:     delti=delti3[1][1];
1.220     brouard  12919:                
                   12920:                
1.126     brouard  12921:     /* 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  12922:                
1.126     brouard  12923:     /* Reads comments: lines beginning with '#' */
                   12924:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12925:       ungetc(c,ficpar);
                   12926:       fgets(line, MAXLINE, ficpar);
                   12927:       numlinepar++;
1.141     brouard  12928:       fputs(line,stdout);
1.126     brouard  12929:       fputs(line,ficparo);
                   12930:       fputs(line,ficlog);
                   12931:     }
                   12932:     ungetc(c,ficpar);
1.220     brouard  12933:                
1.126     brouard  12934:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12935:     hess=matrix(1,npar,1,npar);
1.131     brouard  12936:     for(i=1; i <=npar; i++)
                   12937:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12938:                
1.194     brouard  12939:     /* Scans npar lines */
1.126     brouard  12940:     for(i=1; i <=npar; i++){
1.226     brouard  12941:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12942:       if(count != 3){
1.226     brouard  12943:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12944: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12945: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12946:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12947: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12948: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12949:        exit(1);
1.220     brouard  12950:       }else{
1.226     brouard  12951:        if(mle==1)
                   12952:          printf("%1d%1d%d",i1,j1,jk);
                   12953:       }
                   12954:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12955:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12956:       for(j=1; j <=i; j++){
1.226     brouard  12957:        fscanf(ficpar," %le",&matcov[i][j]);
                   12958:        if(mle==1){
                   12959:          printf(" %.5le",matcov[i][j]);
                   12960:        }
                   12961:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12962:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12963:       }
                   12964:       fscanf(ficpar,"\n");
                   12965:       numlinepar++;
                   12966:       if(mle==1)
1.220     brouard  12967:                                printf("\n");
1.126     brouard  12968:       fprintf(ficlog,"\n");
                   12969:       fprintf(ficparo,"\n");
                   12970:     }
1.194     brouard  12971:     /* End of read covariance matrix npar lines */
1.126     brouard  12972:     for(i=1; i <=npar; i++)
                   12973:       for(j=i+1;j<=npar;j++)
1.226     brouard  12974:        matcov[i][j]=matcov[j][i];
1.126     brouard  12975:     
                   12976:     if(mle==1)
                   12977:       printf("\n");
                   12978:     fprintf(ficlog,"\n");
                   12979:     
                   12980:     fflush(ficlog);
                   12981:     
                   12982:   }    /* End of mle != -3 */
1.218     brouard  12983:   
1.186     brouard  12984:   /*  Main data
                   12985:    */
1.290     brouard  12986:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12987:   /* num=lvector(1,n); */
                   12988:   /* moisnais=vector(1,n); */
                   12989:   /* annais=vector(1,n); */
                   12990:   /* moisdc=vector(1,n); */
                   12991:   /* andc=vector(1,n); */
                   12992:   /* weight=vector(1,n); */
                   12993:   /* agedc=vector(1,n); */
                   12994:   /* cod=ivector(1,n); */
                   12995:   /* for(i=1;i<=n;i++){ */
                   12996:   num=lvector(firstobs,lastobs);
                   12997:   moisnais=vector(firstobs,lastobs);
                   12998:   annais=vector(firstobs,lastobs);
                   12999:   moisdc=vector(firstobs,lastobs);
                   13000:   andc=vector(firstobs,lastobs);
                   13001:   weight=vector(firstobs,lastobs);
                   13002:   agedc=vector(firstobs,lastobs);
                   13003:   cod=ivector(firstobs,lastobs);
                   13004:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13005:     num[i]=0;
                   13006:     moisnais[i]=0;
                   13007:     annais[i]=0;
                   13008:     moisdc[i]=0;
                   13009:     andc[i]=0;
                   13010:     agedc[i]=0;
                   13011:     cod[i]=0;
                   13012:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13013:   }
1.290     brouard  13014:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13015:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13016:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13017:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13018:   tab=ivector(1,NCOVMAX);
1.144     brouard  13019:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13020:   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  13021: 
1.136     brouard  13022:   /* Reads data from file datafile */
                   13023:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13024:     goto end;
                   13025: 
                   13026:   /* Calculation of the number of parameters from char model */
1.234     brouard  13027:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13028:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13029:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13030:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13031:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13032:   */
                   13033:   
                   13034:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13035:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13036:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13037:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13038:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13039:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13040:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13041:   TvarF=ivector(1,NCOVMAX); /*  */
                   13042:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13043:   TvarV=ivector(1,NCOVMAX); /*  */
                   13044:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13045:   TvarA=ivector(1,NCOVMAX); /*  */
                   13046:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13047:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13048:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13049:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13050:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13051:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13052:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13053:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13054:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13055:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13056:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13057: 
1.230     brouard  13058:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13059:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13060:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13061:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13062:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13063:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13064:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13065:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13066:   */
                   13067:   /* For model-covariate k tells which data-covariate to use but
                   13068:     because this model-covariate is a construction we invent a new column
                   13069:     ncovcol + k1
                   13070:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13071:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13072:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13073:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13074:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13075:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13076:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13077:   */
1.145     brouard  13078:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13079:   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  13080:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13081:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13082:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13083:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13084:                         4 covariates (3 plus signs)
                   13085:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13086:                           */  
                   13087:   for(i=1;i<NCOVMAX;i++)
                   13088:     Tage[i]=0;
1.230     brouard  13089:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13090:                                * individual dummy, fixed or varying:
                   13091:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13092:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13093:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13094:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13095:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13096:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13097:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13098:                                * individual quantitative, fixed or varying:
                   13099:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13100:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13101:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13102: /* Main decodemodel */
                   13103: 
1.187     brouard  13104: 
1.223     brouard  13105:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13106:     goto end;
                   13107: 
1.137     brouard  13108:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13109:     nbwarn++;
                   13110:     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); 
                   13111:     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); 
                   13112:   }
1.136     brouard  13113:     /*  if(mle==1){*/
1.137     brouard  13114:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13115:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13116:   }
                   13117: 
                   13118:     /*-calculation of age at interview from date of interview and age at death -*/
                   13119:   agev=matrix(1,maxwav,1,imx);
                   13120: 
                   13121:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13122:     goto end;
                   13123: 
1.126     brouard  13124: 
1.136     brouard  13125:   agegomp=(int)agemin;
1.290     brouard  13126:   free_vector(moisnais,firstobs,lastobs);
                   13127:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13128:   /* free_matrix(mint,1,maxwav,1,n);
                   13129:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13130:   /* free_vector(moisdc,1,n); */
                   13131:   /* free_vector(andc,1,n); */
1.145     brouard  13132:   /* */
                   13133:   
1.126     brouard  13134:   wav=ivector(1,imx);
1.214     brouard  13135:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13136:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13137:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13138:   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.*/
                   13139:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13140:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13141:    
                   13142:   /* Concatenates waves */
1.214     brouard  13143:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13144:      Death is a valid wave (if date is known).
                   13145:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13146:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13147:      and mw[mi+1][i]. dh depends on stepm.
                   13148:   */
                   13149: 
1.126     brouard  13150:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13151:   /* Concatenates waves */
1.145     brouard  13152:  
1.290     brouard  13153:   free_vector(moisdc,firstobs,lastobs);
                   13154:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13155: 
1.126     brouard  13156:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13157:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13158:   ncodemax[1]=1;
1.145     brouard  13159:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13160:   cptcoveff=0;
1.220     brouard  13161:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13162:     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  13163:   }
                   13164:   
                   13165:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13166:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13167:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13168:     invalidvarcomb[i]=0;
                   13169:   
1.211     brouard  13170:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13171:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13172:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13173:   
1.200     brouard  13174:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13175:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13176:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13177:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13178:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13179:    * (currently 0 or 1) in the data.
                   13180:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13181:    * corresponding modality (h,j).
                   13182:    */
                   13183: 
1.145     brouard  13184:   h=0;
                   13185:   /*if (cptcovn > 0) */
1.126     brouard  13186:   m=pow(2,cptcoveff);
                   13187:  
1.144     brouard  13188:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13189:           * For k=4 covariates, h goes from 1 to m=2**k
                   13190:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13191:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13192:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13193:           *______________________________   *______________________
                   13194:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13195:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13196:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13197:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13198:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13199:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13200:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13201:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13202:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13203:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13204:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13205:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13206:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13207:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13208:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13209:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13210:           */                                     
1.212     brouard  13211:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13212:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13213:      * and the value of each covariate?
                   13214:      * V1=1, V2=1, V3=2, V4=1 ?
                   13215:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13216:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13217:      * In order to get the real value in the data, we use nbcode
                   13218:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13219:      * We are keeping this crazy system in order to be able (in the future?) 
                   13220:      * to have more than 2 values (0 or 1) for a covariate.
                   13221:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13222:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13223:      *              bbbbbbbb
                   13224:      *              76543210     
                   13225:      *   h-1        00000101 (6-1=5)
1.219     brouard  13226:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13227:      *           &
                   13228:      *     1        00000001 (1)
1.219     brouard  13229:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13230:      *          +1= 00000001 =1 
1.211     brouard  13231:      *
                   13232:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13233:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13234:      *    >>k'            11
                   13235:      *          &   00000001
                   13236:      *            = 00000001
                   13237:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13238:      * Reverse h=6 and m=16?
                   13239:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13240:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13241:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13242:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13243:      * V3=decodtabm(14,3,2**4)=2
                   13244:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13245:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13246:      *          &1 000000001
                   13247:      *           = 000000001
                   13248:      *         +1= 000000010 =2
                   13249:      *                  2211
                   13250:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13251:      *                  V3=2
1.220     brouard  13252:                 * codtabm and decodtabm are identical
1.211     brouard  13253:      */
                   13254: 
1.145     brouard  13255: 
                   13256:  free_ivector(Ndum,-1,NCOVMAX);
                   13257: 
                   13258: 
1.126     brouard  13259:     
1.186     brouard  13260:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13261:   strcpy(optionfilegnuplot,optionfilefiname);
                   13262:   if(mle==-3)
1.201     brouard  13263:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13264:   strcat(optionfilegnuplot,".gp");
                   13265: 
                   13266:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13267:     printf("Problem with file %s",optionfilegnuplot);
                   13268:   }
                   13269:   else{
1.204     brouard  13270:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13271:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13272:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13273:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13274:   }
                   13275:   /*  fclose(ficgp);*/
1.186     brouard  13276: 
                   13277: 
                   13278:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13279: 
                   13280:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13281:   if(mle==-3)
1.201     brouard  13282:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13283:   strcat(optionfilehtm,".htm");
                   13284:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13285:     printf("Problem with %s \n",optionfilehtm);
                   13286:     exit(0);
1.126     brouard  13287:   }
                   13288: 
                   13289:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13290:   strcat(optionfilehtmcov,"-cov.htm");
                   13291:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13292:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13293:   }
                   13294:   else{
                   13295:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13296: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13297: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13298:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13299:   }
                   13300: 
1.335     brouard  13301:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13302: <title>IMaCh %s</title></head>\n\
                   13303:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13304: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13305: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13306: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13307: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13308:   
                   13309:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13310: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13311: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13312: This file: <a href=\"%s\">%s</a></br>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  13313: \n\
                   13314: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13315:  <ul><li><h4>Parameter files</h4>\n\
                   13316:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13317:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13318:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13319:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13320:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13321:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13322:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13323:          fileres,fileres,\
                   13324:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13325:   fflush(fichtm);
                   13326: 
                   13327:   strcpy(pathr,path);
                   13328:   strcat(pathr,optionfilefiname);
1.184     brouard  13329: #ifdef WIN32
                   13330:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13331: #else
1.126     brouard  13332:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13333: #endif
                   13334:          
1.126     brouard  13335:   
1.220     brouard  13336:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13337:                 and for any valid combination of covariates
1.126     brouard  13338:      and prints on file fileres'p'. */
1.251     brouard  13339:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13340:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13341: 
                   13342:   fprintf(fichtm,"\n");
1.286     brouard  13343:   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  13344:          ftol, stepm);
                   13345:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13346:   ncurrv=1;
                   13347:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13348:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13349:   ncurrv=i;
                   13350:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13351:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13352:   ncurrv=i;
                   13353:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13354:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13355:   ncurrv=i;
                   13356:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13357:   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", \
                   13358:           nlstate, ndeath, maxwav, mle, weightopt);
                   13359: 
                   13360:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13361: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13362: 
                   13363:   
1.317     brouard  13364:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13365: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13366: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13367:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13368:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13369:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13370:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13371:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13372:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13373: 
1.126     brouard  13374:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13375:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13376:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13377: 
                   13378:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13379:   /* For mortality only */
1.126     brouard  13380:   if (mle==-3){
1.136     brouard  13381:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13382:     for(i=1;i<=NDIM;i++)
                   13383:       for(j=1;j<=NDIM;j++)
                   13384:        ximort[i][j]=0.;
1.186     brouard  13385:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13386:     cens=ivector(firstobs,lastobs);
                   13387:     ageexmed=vector(firstobs,lastobs);
                   13388:     agecens=vector(firstobs,lastobs);
                   13389:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13390:                
1.126     brouard  13391:     for (i=1; i<=imx; i++){
                   13392:       dcwave[i]=-1;
                   13393:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13394:        if (s[m][i]>nlstate) {
                   13395:          dcwave[i]=m;
                   13396:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13397:          break;
                   13398:        }
1.126     brouard  13399:     }
1.226     brouard  13400:     
1.126     brouard  13401:     for (i=1; i<=imx; i++) {
                   13402:       if (wav[i]>0){
1.226     brouard  13403:        ageexmed[i]=agev[mw[1][i]][i];
                   13404:        j=wav[i];
                   13405:        agecens[i]=1.; 
                   13406:        
                   13407:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13408:          agecens[i]=agev[mw[j][i]][i];
                   13409:          cens[i]= 1;
                   13410:        }else if (ageexmed[i]< 1) 
                   13411:          cens[i]= -1;
                   13412:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13413:          cens[i]=0 ;
1.126     brouard  13414:       }
                   13415:       else cens[i]=-1;
                   13416:     }
                   13417:     
                   13418:     for (i=1;i<=NDIM;i++) {
                   13419:       for (j=1;j<=NDIM;j++)
1.226     brouard  13420:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13421:     }
                   13422:     
1.302     brouard  13423:     p[1]=0.0268; p[NDIM]=0.083;
                   13424:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13425:     
                   13426:     
1.136     brouard  13427: #ifdef GSL
                   13428:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13429: #else
1.126     brouard  13430:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13431: #endif
1.201     brouard  13432:     strcpy(filerespow,"POW-MORT_"); 
                   13433:     strcat(filerespow,fileresu);
1.126     brouard  13434:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13435:       printf("Problem with resultfile: %s\n", filerespow);
                   13436:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13437:     }
1.136     brouard  13438: #ifdef GSL
                   13439:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13440: #else
1.126     brouard  13441:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13442: #endif
1.126     brouard  13443:     /*  for (i=1;i<=nlstate;i++)
                   13444:        for(j=1;j<=nlstate+ndeath;j++)
                   13445:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13446:     */
                   13447:     fprintf(ficrespow,"\n");
1.136     brouard  13448: #ifdef GSL
                   13449:     /* gsl starts here */ 
                   13450:     T = gsl_multimin_fminimizer_nmsimplex;
                   13451:     gsl_multimin_fminimizer *sfm = NULL;
                   13452:     gsl_vector *ss, *x;
                   13453:     gsl_multimin_function minex_func;
                   13454: 
                   13455:     /* Initial vertex size vector */
                   13456:     ss = gsl_vector_alloc (NDIM);
                   13457:     
                   13458:     if (ss == NULL){
                   13459:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13460:     }
                   13461:     /* Set all step sizes to 1 */
                   13462:     gsl_vector_set_all (ss, 0.001);
                   13463: 
                   13464:     /* Starting point */
1.126     brouard  13465:     
1.136     brouard  13466:     x = gsl_vector_alloc (NDIM);
                   13467:     
                   13468:     if (x == NULL){
                   13469:       gsl_vector_free(ss);
                   13470:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13471:     }
                   13472:   
                   13473:     /* Initialize method and iterate */
                   13474:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13475:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13476:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13477:     gsl_vector_set(x, 0, p[1]);
                   13478:     gsl_vector_set(x, 1, p[2]);
                   13479: 
                   13480:     minex_func.f = &gompertz_f;
                   13481:     minex_func.n = NDIM;
                   13482:     minex_func.params = (void *)&p; /* ??? */
                   13483:     
                   13484:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13485:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13486:     
                   13487:     printf("Iterations beginning .....\n\n");
                   13488:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13489: 
                   13490:     iteri=0;
                   13491:     while (rval == GSL_CONTINUE){
                   13492:       iteri++;
                   13493:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13494:       
                   13495:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13496:       fflush(0);
                   13497:       
                   13498:       if (status) 
                   13499:         break;
                   13500:       
                   13501:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13502:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13503:       
                   13504:       if (rval == GSL_SUCCESS)
                   13505:         printf ("converged to a local maximum at\n");
                   13506:       
                   13507:       printf("%5d ", iteri);
                   13508:       for (it = 0; it < NDIM; it++){
                   13509:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13510:       }
                   13511:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13512:     }
                   13513:     
                   13514:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13515:     
                   13516:     gsl_vector_free(x); /* initial values */
                   13517:     gsl_vector_free(ss); /* inital step size */
                   13518:     for (it=0; it<NDIM; it++){
                   13519:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13520:       fprintf(ficrespow," %.12lf", p[it]);
                   13521:     }
                   13522:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13523: #endif
                   13524: #ifdef POWELL
                   13525:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13526: #endif  
1.126     brouard  13527:     fclose(ficrespow);
                   13528:     
1.203     brouard  13529:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13530: 
                   13531:     for(i=1; i <=NDIM; i++)
                   13532:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13533:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13534:     
                   13535:     printf("\nCovariance matrix\n ");
1.203     brouard  13536:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13537:     for(i=1; i <=NDIM; i++) {
                   13538:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13539:                                printf("%f ",matcov[i][j]);
                   13540:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13541:       }
1.203     brouard  13542:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13543:     }
                   13544:     
                   13545:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13546:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13547:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13548:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13549:     }
1.302     brouard  13550:     lsurv=vector(agegomp,AGESUP);
                   13551:     lpop=vector(agegomp,AGESUP);
                   13552:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13553:     lsurv[agegomp]=100000;
                   13554:     
                   13555:     for (k=agegomp;k<=AGESUP;k++) {
                   13556:       agemortsup=k;
                   13557:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13558:     }
                   13559:     
                   13560:     for (k=agegomp;k<agemortsup;k++)
                   13561:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13562:     
                   13563:     for (k=agegomp;k<agemortsup;k++){
                   13564:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13565:       sumlpop=sumlpop+lpop[k];
                   13566:     }
                   13567:     
                   13568:     tpop[agegomp]=sumlpop;
                   13569:     for (k=agegomp;k<(agemortsup-3);k++){
                   13570:       /*  tpop[k+1]=2;*/
                   13571:       tpop[k+1]=tpop[k]-lpop[k];
                   13572:     }
                   13573:     
                   13574:     
                   13575:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13576:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13577:       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]);
                   13578:     
                   13579:     
                   13580:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13581:                ageminpar=50;
                   13582:                agemaxpar=100;
1.194     brouard  13583:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13584:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13585: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13586: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13587:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13588: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13589: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13590:     }else{
                   13591:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13592:                        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  13593:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13594:                }
1.201     brouard  13595:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13596:                     stepm, weightopt,\
                   13597:                     model,imx,p,matcov,agemortsup);
                   13598:     
1.302     brouard  13599:     free_vector(lsurv,agegomp,AGESUP);
                   13600:     free_vector(lpop,agegomp,AGESUP);
                   13601:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13602:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13603:     free_ivector(dcwave,firstobs,lastobs);
                   13604:     free_vector(agecens,firstobs,lastobs);
                   13605:     free_vector(ageexmed,firstobs,lastobs);
                   13606:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13607: #ifdef GSL
1.136     brouard  13608: #endif
1.186     brouard  13609:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13610:   /* Standard  */
                   13611:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13612:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13613:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13614:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13615:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13616:     for (k=1; k<=npar;k++)
                   13617:       printf(" %d %8.5f",k,p[k]);
                   13618:     printf("\n");
1.205     brouard  13619:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13620:       /* mlikeli uses func not funcone */
1.247     brouard  13621:       /* for(i=1;i<nlstate;i++){ */
                   13622:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13623:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13624:       /* } */
1.205     brouard  13625:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13626:     }
                   13627:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13628:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13629:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13630:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13631:     }
                   13632:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13633:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13634:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13635:           /* exit(0); */
1.126     brouard  13636:     for (k=1; k<=npar;k++)
                   13637:       printf(" %d %8.5f",k,p[k]);
                   13638:     printf("\n");
                   13639:     
                   13640:     /*--------- results files --------------*/
1.283     brouard  13641:     /* 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  13642:     
                   13643:     
                   13644:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13645:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13646:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13647: 
                   13648:     printf("#model=  1      +     age ");
                   13649:     fprintf(ficres,"#model=  1      +     age ");
                   13650:     fprintf(ficlog,"#model=  1      +     age ");
                   13651:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13652: </ul>", model);
                   13653: 
                   13654:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13655:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13656:     if(nagesqr==1){
                   13657:       printf("  + age*age  ");
                   13658:       fprintf(ficres,"  + age*age  ");
                   13659:       fprintf(ficlog,"  + age*age  ");
                   13660:       fprintf(fichtm, "<th>+ age*age</th>");
                   13661:     }
                   13662:     for(j=1;j <=ncovmodel-2;j++){
                   13663:       if(Typevar[j]==0) {
                   13664:        printf("  +      V%d  ",Tvar[j]);
                   13665:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13666:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13667:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13668:       }else if(Typevar[j]==1) {
                   13669:        printf("  +    V%d*age ",Tvar[j]);
                   13670:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13671:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13672:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13673:       }else if(Typevar[j]==2) {
                   13674:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13675:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13676:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13677:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13678:       }
                   13679:     }
                   13680:     printf("\n");
                   13681:     fprintf(ficres,"\n");
                   13682:     fprintf(ficlog,"\n");
                   13683:     fprintf(fichtm, "</tr>");
                   13684:     fprintf(fichtm, "\n");
                   13685:     
                   13686:     
1.126     brouard  13687:     for(i=1,jk=1; i <=nlstate; i++){
                   13688:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13689:        if (k != i) {
1.319     brouard  13690:          fprintf(fichtm, "<tr>");
1.225     brouard  13691:          printf("%d%d ",i,k);
                   13692:          fprintf(ficlog,"%d%d ",i,k);
                   13693:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13694:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13695:          for(j=1; j <=ncovmodel; j++){
                   13696:            printf("%12.7f ",p[jk]);
                   13697:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13698:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13699:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13700:            jk++; 
                   13701:          }
                   13702:          printf("\n");
                   13703:          fprintf(ficlog,"\n");
                   13704:          fprintf(ficres,"\n");
1.319     brouard  13705:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13706:        }
1.126     brouard  13707:       }
                   13708:     }
1.319     brouard  13709:     /* fprintf(fichtm,"</tr>\n"); */
                   13710:     fprintf(fichtm,"</table>\n");
                   13711:     fprintf(fichtm, "\n");
                   13712: 
1.203     brouard  13713:     if(mle != 0){
                   13714:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13715:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13716:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13717:       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");
                   13718:       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  13719:       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  13720:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13721:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13722:       if(nagesqr==1){
                   13723:        printf("  + age*age  ");
                   13724:        fprintf(ficres,"  + age*age  ");
                   13725:        fprintf(ficlog,"  + age*age  ");
                   13726:        fprintf(fichtm, "<th>+ age*age</th>");
                   13727:       }
                   13728:       for(j=1;j <=ncovmodel-2;j++){
                   13729:        if(Typevar[j]==0) {
                   13730:          printf("  +      V%d  ",Tvar[j]);
                   13731:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13732:        }else if(Typevar[j]==1) {
                   13733:          printf("  +    V%d*age ",Tvar[j]);
                   13734:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13735:        }else if(Typevar[j]==2) {
                   13736:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13737:        }
                   13738:       }
                   13739:       fprintf(fichtm, "</tr>\n");
                   13740:  
1.203     brouard  13741:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13742:        for(k=1; k <=(nlstate+ndeath); k++){
                   13743:          if (k != i) {
1.319     brouard  13744:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13745:            printf("%d%d ",i,k);
                   13746:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13747:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13748:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13749:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13750:              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]));
                   13751:              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  13752:              if(fabs(wald) > 1.96){
1.321     brouard  13753:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13754:              }else{
                   13755:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13756:              }
1.324     brouard  13757:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13758:              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  13759:              jk++; 
                   13760:            }
                   13761:            printf("\n");
                   13762:            fprintf(ficlog,"\n");
1.319     brouard  13763:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13764:          }
                   13765:        }
1.193     brouard  13766:       }
1.203     brouard  13767:     } /* end of hesscov and Wald tests */
1.319     brouard  13768:     fprintf(fichtm,"</table>\n");
1.225     brouard  13769:     
1.203     brouard  13770:     /*  */
1.126     brouard  13771:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13772:     printf("# Scales (for hessian or gradient estimation)\n");
                   13773:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13774:     for(i=1,jk=1; i <=nlstate; i++){
                   13775:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13776:        if (j!=i) {
                   13777:          fprintf(ficres,"%1d%1d",i,j);
                   13778:          printf("%1d%1d",i,j);
                   13779:          fprintf(ficlog,"%1d%1d",i,j);
                   13780:          for(k=1; k<=ncovmodel;k++){
                   13781:            printf(" %.5e",delti[jk]);
                   13782:            fprintf(ficlog," %.5e",delti[jk]);
                   13783:            fprintf(ficres," %.5e",delti[jk]);
                   13784:            jk++;
                   13785:          }
                   13786:          printf("\n");
                   13787:          fprintf(ficlog,"\n");
                   13788:          fprintf(ficres,"\n");
                   13789:        }
1.126     brouard  13790:       }
                   13791:     }
                   13792:     
                   13793:     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  13794:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13795:       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");
                   13796:     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");
                   13797:     /* # 121 Var(a12)\n\ */
                   13798:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13799:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13800:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13801:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13802:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13803:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13804:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13805:     
                   13806:     
                   13807:     /* Just to have a covariance matrix which will be more understandable
                   13808:        even is we still don't want to manage dictionary of variables
                   13809:     */
                   13810:     for(itimes=1;itimes<=2;itimes++){
                   13811:       jj=0;
                   13812:       for(i=1; i <=nlstate; i++){
1.225     brouard  13813:        for(j=1; j <=nlstate+ndeath; j++){
                   13814:          if(j==i) continue;
                   13815:          for(k=1; k<=ncovmodel;k++){
                   13816:            jj++;
                   13817:            ca[0]= k+'a'-1;ca[1]='\0';
                   13818:            if(itimes==1){
                   13819:              if(mle>=1)
                   13820:                printf("#%1d%1d%d",i,j,k);
                   13821:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13822:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13823:            }else{
                   13824:              if(mle>=1)
                   13825:                printf("%1d%1d%d",i,j,k);
                   13826:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13827:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13828:            }
                   13829:            ll=0;
                   13830:            for(li=1;li <=nlstate; li++){
                   13831:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13832:                if(lj==li) continue;
                   13833:                for(lk=1;lk<=ncovmodel;lk++){
                   13834:                  ll++;
                   13835:                  if(ll<=jj){
                   13836:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13837:                    if(ll<jj){
                   13838:                      if(itimes==1){
                   13839:                        if(mle>=1)
                   13840:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13841:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13842:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13843:                      }else{
                   13844:                        if(mle>=1)
                   13845:                          printf(" %.5e",matcov[jj][ll]); 
                   13846:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13847:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13848:                      }
                   13849:                    }else{
                   13850:                      if(itimes==1){
                   13851:                        if(mle>=1)
                   13852:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13853:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13854:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13855:                      }else{
                   13856:                        if(mle>=1)
                   13857:                          printf(" %.7e",matcov[jj][ll]); 
                   13858:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13859:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13860:                      }
                   13861:                    }
                   13862:                  }
                   13863:                } /* end lk */
                   13864:              } /* end lj */
                   13865:            } /* end li */
                   13866:            if(mle>=1)
                   13867:              printf("\n");
                   13868:            fprintf(ficlog,"\n");
                   13869:            fprintf(ficres,"\n");
                   13870:            numlinepar++;
                   13871:          } /* end k*/
                   13872:        } /*end j */
1.126     brouard  13873:       } /* end i */
                   13874:     } /* end itimes */
                   13875:     
                   13876:     fflush(ficlog);
                   13877:     fflush(ficres);
1.225     brouard  13878:     while(fgets(line, MAXLINE, ficpar)) {
                   13879:       /* If line starts with a # it is a comment */
                   13880:       if (line[0] == '#') {
                   13881:        numlinepar++;
                   13882:        fputs(line,stdout);
                   13883:        fputs(line,ficparo);
                   13884:        fputs(line,ficlog);
1.299     brouard  13885:        fputs(line,ficres);
1.225     brouard  13886:        continue;
                   13887:       }else
                   13888:        break;
                   13889:     }
                   13890:     
1.209     brouard  13891:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13892:     /*   ungetc(c,ficpar); */
                   13893:     /*   fgets(line, MAXLINE, ficpar); */
                   13894:     /*   fputs(line,stdout); */
                   13895:     /*   fputs(line,ficparo); */
                   13896:     /* } */
                   13897:     /* ungetc(c,ficpar); */
1.126     brouard  13898:     
                   13899:     estepm=0;
1.209     brouard  13900:     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  13901:       
                   13902:       if (num_filled != 6) {
                   13903:        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);
                   13904:        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);
                   13905:        goto end;
                   13906:       }
                   13907:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13908:     }
                   13909:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13910:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13911:     
1.209     brouard  13912:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13913:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13914:     if (fage <= 2) {
                   13915:       bage = ageminpar;
                   13916:       fage = agemaxpar;
                   13917:     }
                   13918:     
                   13919:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13920:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13921:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13922:                
1.186     brouard  13923:     /* Other stuffs, more or less useful */    
1.254     brouard  13924:     while(fgets(line, MAXLINE, ficpar)) {
                   13925:       /* If line starts with a # it is a comment */
                   13926:       if (line[0] == '#') {
                   13927:        numlinepar++;
                   13928:        fputs(line,stdout);
                   13929:        fputs(line,ficparo);
                   13930:        fputs(line,ficlog);
1.299     brouard  13931:        fputs(line,ficres);
1.254     brouard  13932:        continue;
                   13933:       }else
                   13934:        break;
                   13935:     }
                   13936: 
                   13937:     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){
                   13938:       
                   13939:       if (num_filled != 7) {
                   13940:        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);
                   13941:        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);
                   13942:        goto end;
                   13943:       }
                   13944:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13945:       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);
                   13946:       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);
                   13947:       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  13948:     }
1.254     brouard  13949: 
                   13950:     while(fgets(line, MAXLINE, ficpar)) {
                   13951:       /* If line starts with a # it is a comment */
                   13952:       if (line[0] == '#') {
                   13953:        numlinepar++;
                   13954:        fputs(line,stdout);
                   13955:        fputs(line,ficparo);
                   13956:        fputs(line,ficlog);
1.299     brouard  13957:        fputs(line,ficres);
1.254     brouard  13958:        continue;
                   13959:       }else
                   13960:        break;
1.126     brouard  13961:     }
                   13962:     
                   13963:     
                   13964:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13965:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13966:     
1.254     brouard  13967:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13968:       if (num_filled != 1) {
                   13969:        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);
                   13970:        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);
                   13971:        goto end;
                   13972:       }
                   13973:       printf("pop_based=%d\n",popbased);
                   13974:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13975:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13976:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13977:     }
                   13978:      
1.258     brouard  13979:     /* Results */
1.332     brouard  13980:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13981:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13982:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13983:     endishere=0;
1.258     brouard  13984:     nresult=0;
1.308     brouard  13985:     parameterline=0;
1.258     brouard  13986:     do{
                   13987:       if(!fgets(line, MAXLINE, ficpar)){
                   13988:        endishere=1;
1.308     brouard  13989:        parameterline=15;
1.258     brouard  13990:       }else if (line[0] == '#') {
                   13991:        /* If line starts with a # it is a comment */
1.254     brouard  13992:        numlinepar++;
                   13993:        fputs(line,stdout);
                   13994:        fputs(line,ficparo);
                   13995:        fputs(line,ficlog);
1.299     brouard  13996:        fputs(line,ficres);
1.254     brouard  13997:        continue;
1.258     brouard  13998:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13999:        parameterline=11;
1.296     brouard  14000:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14001:        parameterline=12;
1.307     brouard  14002:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14003:        parameterline=13;
1.307     brouard  14004:       }
1.258     brouard  14005:       else{
                   14006:        parameterline=14;
1.254     brouard  14007:       }
1.308     brouard  14008:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14009:       case 11:
1.296     brouard  14010:        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)){
                   14011:                  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  14012:          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);
                   14013:          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);
                   14014:          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);
                   14015:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14016:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14017:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14018:           prvforecast = 1;
                   14019:        } 
                   14020:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14021:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14022:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14023:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14024:           prvforecast = 2;
                   14025:        }
                   14026:        else {
                   14027:          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);
                   14028:          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);
                   14029:          goto end;
1.258     brouard  14030:        }
1.254     brouard  14031:        break;
1.258     brouard  14032:       case 12:
1.296     brouard  14033:        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)){
                   14034:           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);
                   14035:          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);
                   14036:          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);
                   14037:          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);
                   14038:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14039:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14040:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14041:           prvbackcast = 1;
                   14042:        } 
                   14043:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14044:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14045:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14046:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14047:           prvbackcast = 2;
                   14048:        }
                   14049:        else {
                   14050:          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);
                   14051:          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);
                   14052:          goto end;
1.258     brouard  14053:        }
1.230     brouard  14054:        break;
1.258     brouard  14055:       case 13:
1.332     brouard  14056:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14057:        nresult++; /* Sum of resultlines */
1.342     brouard  14058:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14059:        /* removefirstspace(&resultlineori); */
                   14060:        
                   14061:        if(strstr(resultlineori,"v") !=0){
                   14062:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14063:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14064:          return 1;
                   14065:        }
                   14066:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14067:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14068:        if(nresult > MAXRESULTLINESPONE-1){
                   14069:          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);
                   14070:          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  14071:          goto end;
                   14072:        }
1.332     brouard  14073:        
1.310     brouard  14074:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14075:          fprintf(ficparo,"result: %s\n",resultline);
                   14076:          fprintf(ficres,"result: %s\n",resultline);
                   14077:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14078:        } else
                   14079:          goto end;
1.307     brouard  14080:        break;
                   14081:       case 14:
                   14082:        printf("Error: Unknown command '%s'\n",line);
                   14083:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14084:        if(line[0] == ' ' || line[0] == '\n'){
                   14085:          printf("It should not be an empty line '%s'\n",line);
                   14086:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14087:        }         
1.307     brouard  14088:        if(ncovmodel >=2 && nresult==0 ){
                   14089:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14090:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14091:        }
1.307     brouard  14092:        /* goto end; */
                   14093:        break;
1.308     brouard  14094:       case 15:
                   14095:        printf("End of resultlines.\n");
                   14096:        fprintf(ficlog,"End of resultlines.\n");
                   14097:        break;
                   14098:       default: /* parameterline =0 */
1.307     brouard  14099:        nresult=1;
                   14100:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14101:       } /* End switch parameterline */
                   14102:     }while(endishere==0); /* End do */
1.126     brouard  14103:     
1.230     brouard  14104:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14105:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14106:     
                   14107:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14108:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14109:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14110: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14111: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14112:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14113: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14114: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14115:     }else{
1.270     brouard  14116:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14117:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14118:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14119:       if(prvforecast==1){
                   14120:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14121:         jprojd=jproj1;
                   14122:         mprojd=mproj1;
                   14123:         anprojd=anproj1;
                   14124:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14125:         jprojf=jproj2;
                   14126:         mprojf=mproj2;
                   14127:         anprojf=anproj2;
                   14128:       } else if(prvforecast == 2){
                   14129:         dateprojd=dateintmean;
                   14130:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14131:         dateprojf=dateintmean+yrfproj;
                   14132:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14133:       }
                   14134:       if(prvbackcast==1){
                   14135:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14136:         jbackd=jback1;
                   14137:         mbackd=mback1;
                   14138:         anbackd=anback1;
                   14139:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14140:         jbackf=jback2;
                   14141:         mbackf=mback2;
                   14142:         anbackf=anback2;
                   14143:       } else if(prvbackcast == 2){
                   14144:         datebackd=dateintmean;
                   14145:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14146:         datebackf=dateintmean-yrbproj;
                   14147:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14148:       }
                   14149:       
                   14150:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14151:     }
                   14152:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14153:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14154:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14155:                
1.225     brouard  14156:     /*------------ free_vector  -------------*/
                   14157:     /*  chdir(path); */
1.220     brouard  14158:                
1.215     brouard  14159:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14160:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14161:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14162:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14163:     free_lvector(num,firstobs,lastobs);
                   14164:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14165:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14166:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14167:     fclose(ficparo);
                   14168:     fclose(ficres);
1.220     brouard  14169:                
                   14170:                
1.186     brouard  14171:     /* Other results (useful)*/
1.220     brouard  14172:                
                   14173:                
1.126     brouard  14174:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14175:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14176:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14177:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14178:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14179:     fclose(ficrespl);
                   14180: 
                   14181:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14182:     /*#include "hpijx.h"*/
1.332     brouard  14183:     /** 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?*/
                   14184:     /* calls hpxij with combination k */
1.180     brouard  14185:     hPijx(p, bage, fage);
1.145     brouard  14186:     fclose(ficrespij);
1.227     brouard  14187:     
1.220     brouard  14188:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14189:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14190:     k=1;
1.126     brouard  14191:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14192:     
1.269     brouard  14193:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14194:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14195:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14196:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14197:        for(k=1;k<=ncovcombmax;k++)
                   14198:          probs[i][j][k]=0.;
1.269     brouard  14199:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14200:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14201:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14202:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14203:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14204:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14205:          for(k=1;k<=ncovcombmax;k++)
                   14206:            mobaverages[i][j][k]=0.;
1.219     brouard  14207:       mobaverage=mobaverages;
                   14208:       if (mobilav!=0) {
1.235     brouard  14209:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14210:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14211:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14212:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14213:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14214:        }
1.269     brouard  14215:       } else if (mobilavproj !=0) {
1.235     brouard  14216:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14217:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14218:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14219:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14220:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14221:        }
1.269     brouard  14222:       }else{
                   14223:        printf("Internal error moving average\n");
                   14224:        fflush(stdout);
                   14225:        exit(1);
1.219     brouard  14226:       }
                   14227:     }/* end if moving average */
1.227     brouard  14228:     
1.126     brouard  14229:     /*---------- Forecasting ------------------*/
1.296     brouard  14230:     if(prevfcast==1){ 
                   14231:       /*   /\*    if(stepm ==1){*\/ */
                   14232:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14233:       /*This done previously after freqsummary.*/
                   14234:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14235:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14236:       
                   14237:       /* } else if (prvforecast==2){ */
                   14238:       /*   /\*    if(stepm ==1){*\/ */
                   14239:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14240:       /* } */
                   14241:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14242:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14243:     }
1.269     brouard  14244: 
1.296     brouard  14245:     /* Prevbcasting */
                   14246:     if(prevbcast==1){
1.219     brouard  14247:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14248:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14249:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14250: 
                   14251:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14252: 
                   14253:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14254: 
1.219     brouard  14255:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14256:       fclose(ficresplb);
                   14257: 
1.222     brouard  14258:       hBijx(p, bage, fage, mobaverage);
                   14259:       fclose(ficrespijb);
1.219     brouard  14260: 
1.296     brouard  14261:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14262:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14263:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14264:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14265:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14266:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14267: 
                   14268:       
1.269     brouard  14269:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14270: 
                   14271:       
1.269     brouard  14272:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14273:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14274:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14275:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14276:     }    /* end  Prevbcasting */
1.268     brouard  14277:  
1.186     brouard  14278:  
                   14279:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14280: 
1.215     brouard  14281:     free_ivector(wav,1,imx);
                   14282:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14283:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14284:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14285:                
                   14286:                
1.127     brouard  14287:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14288:                
1.201     brouard  14289:     strcpy(filerese,"E_");
                   14290:     strcat(filerese,fileresu);
1.126     brouard  14291:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14292:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14293:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14294:     }
1.208     brouard  14295:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14296:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14297: 
                   14298:     pstamp(ficreseij);
1.219     brouard  14299:                
1.235     brouard  14300:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14301:     if (cptcovn < 1){i1=1;}
                   14302:     
                   14303:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14304:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14305:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14306:        continue;
1.219     brouard  14307:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14308:       printf("\n#****** ");
1.225     brouard  14309:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14310:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14311:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14312:       }
                   14313:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14314:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14315:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14316:       }
                   14317:       fprintf(ficreseij,"******\n");
1.235     brouard  14318:       printf("******\n");
1.219     brouard  14319:       
                   14320:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14321:       oldm=oldms;savm=savms;
1.330     brouard  14322:       /* 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  14323:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14324:       
1.219     brouard  14325:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14326:     }
                   14327:     fclose(ficreseij);
1.208     brouard  14328:     printf("done evsij\n");fflush(stdout);
                   14329:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14330: 
1.218     brouard  14331:                
1.227     brouard  14332:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14333:     /* Should be moved in a function */                
1.201     brouard  14334:     strcpy(filerest,"T_");
                   14335:     strcat(filerest,fileresu);
1.127     brouard  14336:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14337:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14338:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14339:     }
1.208     brouard  14340:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14341:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14342:     strcpy(fileresstde,"STDE_");
                   14343:     strcat(fileresstde,fileresu);
1.126     brouard  14344:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14345:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14346:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14347:     }
1.227     brouard  14348:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14349:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14350: 
1.201     brouard  14351:     strcpy(filerescve,"CVE_");
                   14352:     strcat(filerescve,fileresu);
1.126     brouard  14353:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14354:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14355:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14356:     }
1.227     brouard  14357:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14358:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14359: 
1.201     brouard  14360:     strcpy(fileresv,"V_");
                   14361:     strcat(fileresv,fileresu);
1.126     brouard  14362:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14363:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14364:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14365:     }
1.227     brouard  14366:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14367:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14368: 
1.235     brouard  14369:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14370:     if (cptcovn < 1){i1=1;}
                   14371:     
1.334     brouard  14372:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14373:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14374:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14375:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14376:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14377:       /* */
                   14378:       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  14379:        continue;
1.321     brouard  14380:       printf("\n# model %s \n#****** Result for:", model);
                   14381:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14382:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14383:       /* It might not be a good idea to mix dummies and quantitative */
                   14384:       /* 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 *\/ */
                   14385:       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 */
                   14386:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14387:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14388:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14389:         * (V5 is quanti) V4 and V3 are dummies
                   14390:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14391:         *                                                              l=1 l=2
                   14392:         *                                                           k=1  1   1   0   0
                   14393:         *                                                           k=2  2   1   1   0
                   14394:         *                                                           k=3 [1] [2]  0   1
                   14395:         *                                                           k=4  2   2   1   1
                   14396:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14397:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14398:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14399:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14400:         */
                   14401:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14402:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14403: /* We give up with the combinations!! */
1.342     brouard  14404:        /* if(debugILK) */
                   14405:        /*   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 *\/ */
1.334     brouard  14406: 
                   14407:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.344     brouard  14408:          /* printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /\* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
                   14409:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
                   14410:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14411:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14412:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14413:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14414:          }else{
                   14415:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14416:          }
                   14417:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14418:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14419:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14420:          /* For each selected (single) quantitative value */
1.337     brouard  14421:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14422:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14423:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14424:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14425:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14426:          }else{
                   14427:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14428:          }
                   14429:        }else{
                   14430:          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 */
                   14431:          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 */
                   14432:          exit(1);
                   14433:        }
1.335     brouard  14434:       } /* End loop for each variable in the resultline */
1.334     brouard  14435:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14436:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14437:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14438:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14439:       /* }      */
1.208     brouard  14440:       fprintf(ficrest,"******\n");
1.227     brouard  14441:       fprintf(ficlog,"******\n");
                   14442:       printf("******\n");
1.208     brouard  14443:       
                   14444:       fprintf(ficresstdeij,"\n#****** ");
                   14445:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14446:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14447:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14448:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14449:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14450:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14451:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14452:       }
                   14453:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
1.337     brouard  14454:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14455:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14456:       }        
1.208     brouard  14457:       fprintf(ficresstdeij,"******\n");
                   14458:       fprintf(ficrescveij,"******\n");
                   14459:       
                   14460:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14461:       /* pstamp(ficresvij); */
1.225     brouard  14462:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14463:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14464:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14465:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14466:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14467:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14468:       }        
1.208     brouard  14469:       fprintf(ficresvij,"******\n");
                   14470:       
                   14471:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14472:       oldm=oldms;savm=savms;
1.235     brouard  14473:       printf(" cvevsij ");
                   14474:       fprintf(ficlog, " cvevsij ");
                   14475:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14476:       printf(" end cvevsij \n ");
                   14477:       fprintf(ficlog, " end cvevsij \n ");
                   14478:       
                   14479:       /*
                   14480:        */
                   14481:       /* goto endfree; */
                   14482:       
                   14483:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14484:       pstamp(ficrest);
                   14485:       
1.269     brouard  14486:       epj=vector(1,nlstate+1);
1.208     brouard  14487:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14488:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14489:        cptcod= 0; /* To be deleted */
                   14490:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14491:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14492:        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  14493:        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 ");
                   14494:        if(vpopbased==1)
                   14495:          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);
                   14496:        else
1.288     brouard  14497:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14498:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14499:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14500:        fprintf(ficrest,"\n");
                   14501:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14502:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14503:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14504:        for(age=bage; age <=fage ;age++){
1.235     brouard  14505:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14506:          if (vpopbased==1) {
                   14507:            if(mobilav ==0){
                   14508:              for(i=1; i<=nlstate;i++)
                   14509:                prlim[i][i]=probs[(int)age][i][k];
                   14510:            }else{ /* mobilav */ 
                   14511:              for(i=1; i<=nlstate;i++)
                   14512:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14513:            }
                   14514:          }
1.219     brouard  14515:          
1.227     brouard  14516:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14517:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14518:          /* printf(" age %4.0f ",age); */
                   14519:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14520:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14521:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14522:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14523:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14524:            }
                   14525:            epj[nlstate+1] +=epj[j];
                   14526:          }
                   14527:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14528:          
1.227     brouard  14529:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14530:            for(j=1;j <=nlstate;j++)
                   14531:              vepp += vareij[i][j][(int)age];
                   14532:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14533:          for(j=1;j <=nlstate;j++){
                   14534:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14535:          }
                   14536:          fprintf(ficrest,"\n");
                   14537:        }
1.208     brouard  14538:       } /* End vpopbased */
1.269     brouard  14539:       free_vector(epj,1,nlstate+1);
1.208     brouard  14540:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14541:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14542:       printf("done selection\n");fflush(stdout);
                   14543:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14544:       
1.335     brouard  14545:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14546: 
                   14547:     printf("done State-specific expectancies\n");fflush(stdout);
                   14548:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14549: 
1.335     brouard  14550:     /* variance-covariance of forward period prevalence */
1.269     brouard  14551:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14552: 
1.227     brouard  14553:     
1.290     brouard  14554:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14555:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14556:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14557:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14558:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14559:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14560:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14561:     free_ivector(tab,1,NCOVMAX);
                   14562:     fclose(ficresstdeij);
                   14563:     fclose(ficrescveij);
                   14564:     fclose(ficresvij);
                   14565:     fclose(ficrest);
                   14566:     fclose(ficpar);
                   14567:     
                   14568:     
1.126     brouard  14569:     /*---------- End : free ----------------*/
1.219     brouard  14570:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14571:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14572:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14573:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14574:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14575:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14576:   /* endfree:*/
                   14577:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14578:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14579:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14580:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14581:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14582:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14583:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14584:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14585:   free_matrix(matcov,1,npar,1,npar);
                   14586:   free_matrix(hess,1,npar,1,npar);
                   14587:   /*free_vector(delti,1,npar);*/
                   14588:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14589:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14590:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14591:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14592:   
                   14593:   free_ivector(ncodemax,1,NCOVMAX);
                   14594:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14595:   free_ivector(Dummy,-1,NCOVMAX);
                   14596:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14597:   free_ivector(DummyV,1,NCOVMAX);
                   14598:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14599:   free_ivector(Typevar,-1,NCOVMAX);
                   14600:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14601:   free_ivector(TvarsQ,1,NCOVMAX);
                   14602:   free_ivector(TvarsQind,1,NCOVMAX);
                   14603:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14604:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14605:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14606:   free_ivector(TvarFD,1,NCOVMAX);
                   14607:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14608:   free_ivector(TvarF,1,NCOVMAX);
                   14609:   free_ivector(TvarFind,1,NCOVMAX);
                   14610:   free_ivector(TvarV,1,NCOVMAX);
                   14611:   free_ivector(TvarVind,1,NCOVMAX);
                   14612:   free_ivector(TvarA,1,NCOVMAX);
                   14613:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14614:   free_ivector(TvarFQ,1,NCOVMAX);
                   14615:   free_ivector(TvarFQind,1,NCOVMAX);
                   14616:   free_ivector(TvarVD,1,NCOVMAX);
                   14617:   free_ivector(TvarVDind,1,NCOVMAX);
                   14618:   free_ivector(TvarVQ,1,NCOVMAX);
                   14619:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14620:   free_ivector(TvarVV,1,NCOVMAX);
                   14621:   free_ivector(TvarVVind,1,NCOVMAX);
                   14622:   
1.230     brouard  14623:   free_ivector(Tvarsel,1,NCOVMAX);
                   14624:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14625:   free_ivector(Tposprod,1,NCOVMAX);
                   14626:   free_ivector(Tprod,1,NCOVMAX);
                   14627:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14628:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14629:   free_ivector(Tage,1,NCOVMAX);
                   14630:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14631:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14632:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14633: 
                   14634:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14635: 
1.227     brouard  14636:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14637:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14638:   fflush(fichtm);
                   14639:   fflush(ficgp);
                   14640:   
1.227     brouard  14641:   
1.126     brouard  14642:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14643:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14644:     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  14645:   }else{
                   14646:     printf("End of Imach\n");
                   14647:     fprintf(ficlog,"End of Imach\n");
                   14648:   }
                   14649:   printf("See log file on %s\n",filelog);
                   14650:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14651:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14652:   rend_time = time(NULL);  
                   14653:   end_time = *localtime(&rend_time);
                   14654:   /* tml = *localtime(&end_time.tm_sec); */
                   14655:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14656:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14657:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14658:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14659:   
1.157     brouard  14660:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14661:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14662:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14663:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14664: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14665:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14666:   fclose(fichtm);
                   14667:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14668:   fclose(fichtmcov);
                   14669:   fclose(ficgp);
                   14670:   fclose(ficlog);
                   14671:   /*------ End -----------*/
1.227     brouard  14672:   
1.281     brouard  14673: 
                   14674: /* Executes gnuplot */
1.227     brouard  14675:   
                   14676:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14677: #ifdef WIN32
1.227     brouard  14678:   if (_chdir(pathcd) != 0)
                   14679:     printf("Can't move to directory %s!\n",path);
                   14680:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14681: #else
1.227     brouard  14682:     if(chdir(pathcd) != 0)
                   14683:       printf("Can't move to directory %s!\n", path);
                   14684:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14685: #endif 
1.126     brouard  14686:     printf("Current directory %s!\n",pathcd);
                   14687:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14688:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14689: #ifdef _WIN32
1.126     brouard  14690:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14691: #endif
                   14692:   if(!stat(plotcmd,&info)){
1.158     brouard  14693:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14694:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14695:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14696:     }else
                   14697:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14698: #ifdef __unix
1.126     brouard  14699:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14700:     if(!stat(plotcmd,&info)){
1.158     brouard  14701:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14702:     }else
                   14703:       strcpy(pplotcmd,plotcmd);
                   14704: #endif
                   14705:   }else
                   14706:     strcpy(pplotcmd,plotcmd);
                   14707:   
                   14708:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14709:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14710:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14711:   
1.126     brouard  14712:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14713:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14714:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14715:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14716:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14717:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14718:       strcpy(plotcmd,pplotcmd);
                   14719:     }
1.126     brouard  14720:   }
1.158     brouard  14721:   printf(" Successful, please wait...");
1.126     brouard  14722:   while (z[0] != 'q') {
                   14723:     /* chdir(path); */
1.154     brouard  14724:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14725:     scanf("%s",z);
                   14726: /*     if (z[0] == 'c') system("./imach"); */
                   14727:     if (z[0] == 'e') {
1.158     brouard  14728: #ifdef __APPLE__
1.152     brouard  14729:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14730: #elif __linux
                   14731:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14732: #else
1.152     brouard  14733:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14734: #endif
                   14735:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14736:       system(pplotcmd);
1.126     brouard  14737:     }
                   14738:     else if (z[0] == 'g') system(plotcmd);
                   14739:     else if (z[0] == 'q') exit(0);
                   14740:   }
1.227     brouard  14741: end:
1.126     brouard  14742:   while (z[0] != 'q') {
1.195     brouard  14743:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14744:     scanf("%s",z);
                   14745:   }
1.283     brouard  14746:   printf("End\n");
1.282     brouard  14747:   exit(0);
1.126     brouard  14748: }

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