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

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.349   ! brouard  1317: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. 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.349   ! brouard  1328: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  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.349   ! brouard  1362: char copyright[]="January 2023,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 */
1.349   ! brouard  1376: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
        !          1377: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
        !          1378: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1379: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1380: 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  1381: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1382: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1383: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349   ! brouard  1384: int ncovvta=0; /*  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
        !          1385: int ncovta=0; /*age*V3*V2 +age*V2+agev3+ageV4  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
        !          1386: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
        !          1387: int ncovva=0; /* +age*V6 + age*V7+ge*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
1.234     brouard  1388: int nsd=0; /**< Total number of single dummy variables (output) */
                   1389: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1390: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1391: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1392: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1393: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1394: int cptcov=0; /* Working variable */
1.334     brouard  1395: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1396: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1397: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1398: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1399: int nlstate=2; /* Number of live states */
                   1400: int ndeath=1; /* Number of dead states */
1.130     brouard  1401: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1402: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1403: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1404: int popbased=0;
                   1405: 
                   1406: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1407: int maxwav=0; /* Maxim number of waves */
                   1408: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1409: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1410: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1411:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1412: int mle=1, weightopt=0;
1.126     brouard  1413: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1414: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1415: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1416:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1417: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1418: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1419: 
1.130     brouard  1420: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1421: double **matprod2(); /* test */
1.126     brouard  1422: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1423: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1424: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1425: 
1.136     brouard  1426: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1427: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1428: FILE *ficlog, *ficrespow;
1.130     brouard  1429: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1430: double fretone; /* Only one call to likelihood */
1.130     brouard  1431: long ipmx=0; /* Number of contributions */
1.126     brouard  1432: double sw; /* Sum of weights */
                   1433: char filerespow[FILENAMELENGTH];
                   1434: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1435: FILE *ficresilk;
                   1436: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1437: FILE *ficresprobmorprev;
                   1438: FILE *fichtm, *fichtmcov; /* Html File */
                   1439: FILE *ficreseij;
                   1440: char filerese[FILENAMELENGTH];
                   1441: FILE *ficresstdeij;
                   1442: char fileresstde[FILENAMELENGTH];
                   1443: FILE *ficrescveij;
                   1444: char filerescve[FILENAMELENGTH];
                   1445: FILE  *ficresvij;
                   1446: char fileresv[FILENAMELENGTH];
1.269     brouard  1447: 
1.126     brouard  1448: char title[MAXLINE];
1.234     brouard  1449: char model[MAXLINE]; /**< The model line */
1.217     brouard  1450: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1451: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1452: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1453: char command[FILENAMELENGTH];
                   1454: int  outcmd=0;
                   1455: 
1.217     brouard  1456: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1457: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1458: char filelog[FILENAMELENGTH]; /* Log file */
                   1459: char filerest[FILENAMELENGTH];
                   1460: char fileregp[FILENAMELENGTH];
                   1461: char popfile[FILENAMELENGTH];
                   1462: 
                   1463: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1464: 
1.157     brouard  1465: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1466: /* struct timezone tzp; */
                   1467: /* extern int gettimeofday(); */
                   1468: struct tm tml, *gmtime(), *localtime();
                   1469: 
                   1470: extern time_t time();
                   1471: 
                   1472: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1473: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349   ! brouard  1474: time_t   rlast_btime; /* raw time */
1.157     brouard  1475: struct tm tm;
                   1476: 
1.126     brouard  1477: char strcurr[80], strfor[80];
                   1478: 
                   1479: char *endptr;
                   1480: long lval;
                   1481: double dval;
                   1482: 
                   1483: #define NR_END 1
                   1484: #define FREE_ARG char*
                   1485: #define FTOL 1.0e-10
                   1486: 
                   1487: #define NRANSI 
1.240     brouard  1488: #define ITMAX 200
                   1489: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1490: 
                   1491: #define TOL 2.0e-4 
                   1492: 
                   1493: #define CGOLD 0.3819660 
                   1494: #define ZEPS 1.0e-10 
                   1495: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1496: 
                   1497: #define GOLD 1.618034 
                   1498: #define GLIMIT 100.0 
                   1499: #define TINY 1.0e-20 
                   1500: 
                   1501: static double maxarg1,maxarg2;
                   1502: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1503: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1504:   
                   1505: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1506: #define rint(a) floor(a+0.5)
1.166     brouard  1507: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1508: #define mytinydouble 1.0e-16
1.166     brouard  1509: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1510: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1511: /* static double dsqrarg; */
                   1512: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1513: static double sqrarg;
                   1514: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1515: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1516: int agegomp= AGEGOMP;
                   1517: 
                   1518: int imx; 
                   1519: int stepm=1;
                   1520: /* Stepm, step in month: minimum step interpolation*/
                   1521: 
                   1522: int estepm;
                   1523: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1524: 
                   1525: int m,nb;
                   1526: long *num;
1.197     brouard  1527: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1528: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1529:                   covariate for which somebody answered excluding 
                   1530:                   undefined. Usually 2: 0 and 1. */
                   1531: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1532:                             covariate for which somebody answered including 
                   1533:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1534: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1535: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1536: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1537: 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  1538: double *ageexmed,*agecens;
                   1539: double dateintmean=0;
1.296     brouard  1540:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1541:   double anprojf, mprojf, jprojf;
1.126     brouard  1542: 
1.296     brouard  1543:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1544:   double anbackf, mbackf, jbackf;
                   1545:   double jintmean,mintmean,aintmean;  
1.126     brouard  1546: double *weight;
                   1547: int **s; /* Status */
1.141     brouard  1548: double *agedc;
1.145     brouard  1549: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1550:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1551:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1552: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1553: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1554: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1555: double  idx; 
                   1556: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1557: /* Some documentation */
                   1558:       /*   Design original data
                   1559:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1560:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1561:        *                                                             ntv=3     nqtv=1
1.330     brouard  1562:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1563:        * For time varying covariate, quanti or dummies
                   1564:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1565:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1566:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1567:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1568:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1569:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1570:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1571:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1572:        */
                   1573: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1574: /* 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
                   1575:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1576:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1577: */
1.349   ! brouard  1578: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
        !          1579: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
        !          1580: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
        !          1581:                                                                /* fixed or varying), 1 for age product, 2 for*/
        !          1582:                                                                /* product without age, 3 for age and double product   */
        !          1583: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
        !          1584:                                                                 /*(single or product without age), 2 dummy*/
        !          1585:                                                                /* with age product, 3 quant with age product*/
        !          1586: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
        !          1587: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
        !          1588: /*TnsdVar[Tvar]   1   2                               3 */ 
        !          1589: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
        !          1590: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
        !          1591: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
        !          1592: /*    nsq      1                     2                  */ /* Counting single quantit tv */
        !          1593: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
        !          1594: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
        !          1595: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
        !          1596: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
        !          1597: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
        !          1598: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1599: /* 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  1600: /* 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  1601: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1602: /* Type                    */
                   1603: /* V         1  2  3  4  5 */
                   1604: /*           F  F  V  V  V */
                   1605: /*           D  Q  D  D  Q */
                   1606: /*                         */
                   1607: int *TvarsD;
1.330     brouard  1608: int *TnsdVar;
1.234     brouard  1609: int *TvarsDind;
                   1610: int *TvarsQ;
                   1611: int *TvarsQind;
                   1612: 
1.318     brouard  1613: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1614: int nresult=0;
1.258     brouard  1615: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1616: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1617: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1618: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1619: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1620: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1621: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1622: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1623: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1624: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1625: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1626: 
                   1627: /* 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
                   1628:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1629:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1630: */
1.234     brouard  1631: /* 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  1632: 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 */
                   1633: 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 */
                   1634: 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 */
                   1635: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1636: 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 */
                   1637: 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  1638: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1639: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1640: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1641: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1642: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1643: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1644: 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 */
                   1645: 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  1646: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1647: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349   ! brouard  1648: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
        !          1649: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
        !          1650: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
        !          1651: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1652:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349   ! brouard  1653:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
        !          1654:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          1655:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
        !          1656:       /* TvarVVind={2,5,5,6,6}, for V3 and then the product V1*V3 is decomposed into V1 and V3 and V1*V3*age into 6,6 */              
1.230     brouard  1657: int *Tvarsel; /**< Selected covariates for output */
                   1658: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349   ! brouard  1659: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
1.227     brouard  1660: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1661: 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  1662: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1663: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1664: int *Tage;
1.227     brouard  1665: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1666: 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  1667: 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*/ 
                   1668: 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  1669: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1670: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1671: int **Tvard;
1.330     brouard  1672: int **Tvardk;
1.227     brouard  1673: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1674: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1675: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1676:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1677:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1678: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1679: double *lsurv, *lpop, *tpop;
                   1680: 
1.231     brouard  1681: #define FD 1; /* Fixed dummy covariate */
                   1682: #define FQ 2; /* Fixed quantitative covariate */
                   1683: #define FP 3; /* Fixed product covariate */
                   1684: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1685: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1686: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1687: #define VD 10; /* Varying dummy covariate */
                   1688: #define VQ 11; /* Varying quantitative covariate */
                   1689: #define VP 12; /* Varying product covariate */
                   1690: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1691: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1692: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1693: #define APFD 16; /* Age product * fixed dummy covariate */
                   1694: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1695: #define APVD 18; /* Age product * varying dummy covariate */
                   1696: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1697: 
                   1698: #define FTYPE 1; /* Fixed covariate */
                   1699: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1700: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1701: 
                   1702: struct kmodel{
                   1703:        int maintype; /* main type */
                   1704:        int subtype; /* subtype */
                   1705: };
                   1706: struct kmodel modell[NCOVMAX];
                   1707: 
1.143     brouard  1708: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1709: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1710: 
                   1711: /**************** split *************************/
                   1712: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1713: {
                   1714:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1715:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1716:   */ 
                   1717:   char *ss;                            /* pointer */
1.186     brouard  1718:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1719: 
                   1720:   l1 = strlen(path );                  /* length of path */
                   1721:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1722:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1723:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1724:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1725:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1726:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1727:     /* get current working directory */
                   1728:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1729: #ifdef WIN32
                   1730:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1731: #else
                   1732:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1733: #endif
1.126     brouard  1734:       return( GLOCK_ERROR_GETCWD );
                   1735:     }
                   1736:     /* got dirc from getcwd*/
                   1737:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1738:   } else {                             /* strip directory from path */
1.126     brouard  1739:     ss++;                              /* after this, the filename */
                   1740:     l2 = strlen( ss );                 /* length of filename */
                   1741:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1742:     strcpy( name, ss );                /* save file name */
                   1743:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1744:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1745:     printf(" DIRC2 = %s \n",dirc);
                   1746:   }
                   1747:   /* We add a separator at the end of dirc if not exists */
                   1748:   l1 = strlen( dirc );                 /* length of directory */
                   1749:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1750:     dirc[l1] =  DIRSEPARATOR;
                   1751:     dirc[l1+1] = 0; 
                   1752:     printf(" DIRC3 = %s \n",dirc);
                   1753:   }
                   1754:   ss = strrchr( name, '.' );           /* find last / */
                   1755:   if (ss >0){
                   1756:     ss++;
                   1757:     strcpy(ext,ss);                    /* save extension */
                   1758:     l1= strlen( name);
                   1759:     l2= strlen(ss)+1;
                   1760:     strncpy( finame, name, l1-l2);
                   1761:     finame[l1-l2]= 0;
                   1762:   }
                   1763: 
                   1764:   return( 0 );                         /* we're done */
                   1765: }
                   1766: 
                   1767: 
                   1768: /******************************************/
                   1769: 
                   1770: void replace_back_to_slash(char *s, char*t)
                   1771: {
                   1772:   int i;
                   1773:   int lg=0;
                   1774:   i=0;
                   1775:   lg=strlen(t);
                   1776:   for(i=0; i<= lg; i++) {
                   1777:     (s[i] = t[i]);
                   1778:     if (t[i]== '\\') s[i]='/';
                   1779:   }
                   1780: }
                   1781: 
1.132     brouard  1782: char *trimbb(char *out, char *in)
1.137     brouard  1783: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1784:   char *s;
                   1785:   s=out;
                   1786:   while (*in != '\0'){
1.137     brouard  1787:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1788:       in++;
                   1789:     }
                   1790:     *out++ = *in++;
                   1791:   }
                   1792:   *out='\0';
                   1793:   return s;
                   1794: }
                   1795: 
1.187     brouard  1796: /* char *substrchaine(char *out, char *in, char *chain) */
                   1797: /* { */
                   1798: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1799: /*   char *s, *t; */
                   1800: /*   t=in;s=out; */
                   1801: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1802: /*     *out++ = *in++; */
                   1803: /*   } */
                   1804: 
                   1805: /*   /\* *in matches *chain *\/ */
                   1806: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1807: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1808: /*   } */
                   1809: /*   in--; chain--; */
                   1810: /*   while ( (*in != '\0')){ */
                   1811: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1812: /*     *out++ = *in++; */
                   1813: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1814: /*   } */
                   1815: /*   *out='\0'; */
                   1816: /*   out=s; */
                   1817: /*   return out; */
                   1818: /* } */
                   1819: char *substrchaine(char *out, char *in, char *chain)
                   1820: {
                   1821:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349   ! brouard  1822:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1823: 
                   1824:   char *strloc;
                   1825: 
1.349   ! brouard  1826:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
        !          1827:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
        !          1828:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out); /* strloc=+age*age+V2 chain="+age*age", out="V1+V1*age+age*age+V2" */
1.187     brouard  1829:   if(strloc != NULL){ 
1.349   ! brouard  1830:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
        !          1831:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1); /* move number of bytes corresponding to the length of "+V2" which is 3, plus one is 4 (including the null)*/
        !          1832:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1833:   }
1.349   ! brouard  1834:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);  /* strloc=+V2 chain="+age*age", in="V1+V1*age+age*age+V2", out="V1+V1*age+V2" */
1.187     brouard  1835:   return out;
                   1836: }
                   1837: 
                   1838: 
1.145     brouard  1839: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1840: {
1.187     brouard  1841:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349   ! brouard  1842:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1843:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1844:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1845:   */
1.160     brouard  1846:   char *s, *t;
1.145     brouard  1847:   t=in;s=in;
                   1848:   while ((*in != occ) && (*in != '\0')){
                   1849:     *alocc++ = *in++;
                   1850:   }
                   1851:   if( *in == occ){
                   1852:     *(alocc)='\0';
                   1853:     s=++in;
                   1854:   }
                   1855:  
                   1856:   if (s == t) {/* occ not found */
                   1857:     *(alocc-(in-s))='\0';
                   1858:     in=s;
                   1859:   }
                   1860:   while ( *in != '\0'){
                   1861:     *blocc++ = *in++;
                   1862:   }
                   1863: 
                   1864:   *blocc='\0';
                   1865:   return t;
                   1866: }
1.137     brouard  1867: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1868: {
1.187     brouard  1869:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1870:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1871:      gives blocc="abcdef2ghi" and alocc="j".
                   1872:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1873:   */
                   1874:   char *s, *t;
                   1875:   t=in;s=in;
                   1876:   while (*in != '\0'){
                   1877:     while( *in == occ){
                   1878:       *blocc++ = *in++;
                   1879:       s=in;
                   1880:     }
                   1881:     *blocc++ = *in++;
                   1882:   }
                   1883:   if (s == t) /* occ not found */
                   1884:     *(blocc-(in-s))='\0';
                   1885:   else
                   1886:     *(blocc-(in-s)-1)='\0';
                   1887:   in=s;
                   1888:   while ( *in != '\0'){
                   1889:     *alocc++ = *in++;
                   1890:   }
                   1891: 
                   1892:   *alocc='\0';
                   1893:   return s;
                   1894: }
                   1895: 
1.126     brouard  1896: int nbocc(char *s, char occ)
                   1897: {
                   1898:   int i,j=0;
                   1899:   int lg=20;
                   1900:   i=0;
                   1901:   lg=strlen(s);
                   1902:   for(i=0; i<= lg; i++) {
1.234     brouard  1903:     if  (s[i] == occ ) j++;
1.126     brouard  1904:   }
                   1905:   return j;
                   1906: }
                   1907: 
1.349   ! brouard  1908: int nboccstr(char *textin, char *chain)
        !          1909: {
        !          1910:   /* Counts the number of occurence of "chain"  in string textin */
        !          1911:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
        !          1912:   char *strloc;
        !          1913:   
        !          1914:   int i,j=0;
        !          1915: 
        !          1916:   i=0;
        !          1917: 
        !          1918:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
        !          1919:   for(;;) {
        !          1920:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
        !          1921:     if(strloc != NULL){
        !          1922:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
        !          1923:       j++;
        !          1924:     }else
        !          1925:       break;
        !          1926:   }
        !          1927:   return j;
        !          1928:   
        !          1929: }
1.137     brouard  1930: /* void cutv(char *u,char *v, char*t, char occ) */
                   1931: /* { */
                   1932: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1933: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1934: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1935: /*   int i,lg,j,p=0; */
                   1936: /*   i=0; */
                   1937: /*   lg=strlen(t); */
                   1938: /*   for(j=0; j<=lg-1; j++) { */
                   1939: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1940: /*   } */
1.126     brouard  1941: 
1.137     brouard  1942: /*   for(j=0; j<p; j++) { */
                   1943: /*     (u[j] = t[j]); */
                   1944: /*   } */
                   1945: /*      u[p]='\0'; */
1.126     brouard  1946: 
1.137     brouard  1947: /*    for(j=0; j<= lg; j++) { */
                   1948: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1949: /*   } */
                   1950: /* } */
1.126     brouard  1951: 
1.160     brouard  1952: #ifdef _WIN32
                   1953: char * strsep(char **pp, const char *delim)
                   1954: {
                   1955:   char *p, *q;
                   1956:          
                   1957:   if ((p = *pp) == NULL)
                   1958:     return 0;
                   1959:   if ((q = strpbrk (p, delim)) != NULL)
                   1960:   {
                   1961:     *pp = q + 1;
                   1962:     *q = '\0';
                   1963:   }
                   1964:   else
                   1965:     *pp = 0;
                   1966:   return p;
                   1967: }
                   1968: #endif
                   1969: 
1.126     brouard  1970: /********************** nrerror ********************/
                   1971: 
                   1972: void nrerror(char error_text[])
                   1973: {
                   1974:   fprintf(stderr,"ERREUR ...\n");
                   1975:   fprintf(stderr,"%s\n",error_text);
                   1976:   exit(EXIT_FAILURE);
                   1977: }
                   1978: /*********************** vector *******************/
                   1979: double *vector(int nl, int nh)
                   1980: {
                   1981:   double *v;
                   1982:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1983:   if (!v) nrerror("allocation failure in vector");
                   1984:   return v-nl+NR_END;
                   1985: }
                   1986: 
                   1987: /************************ free vector ******************/
                   1988: void free_vector(double*v, int nl, int nh)
                   1989: {
                   1990:   free((FREE_ARG)(v+nl-NR_END));
                   1991: }
                   1992: 
                   1993: /************************ivector *******************************/
                   1994: int *ivector(long nl,long nh)
                   1995: {
                   1996:   int *v;
                   1997:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1998:   if (!v) nrerror("allocation failure in ivector");
                   1999:   return v-nl+NR_END;
                   2000: }
                   2001: 
                   2002: /******************free ivector **************************/
                   2003: void free_ivector(int *v, long nl, long nh)
                   2004: {
                   2005:   free((FREE_ARG)(v+nl-NR_END));
                   2006: }
                   2007: 
                   2008: /************************lvector *******************************/
                   2009: long *lvector(long nl,long nh)
                   2010: {
                   2011:   long *v;
                   2012:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2013:   if (!v) nrerror("allocation failure in ivector");
                   2014:   return v-nl+NR_END;
                   2015: }
                   2016: 
                   2017: /******************free lvector **************************/
                   2018: void free_lvector(long *v, long nl, long nh)
                   2019: {
                   2020:   free((FREE_ARG)(v+nl-NR_END));
                   2021: }
                   2022: 
                   2023: /******************* imatrix *******************************/
                   2024: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2025:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2026: { 
                   2027:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2028:   int **m; 
                   2029:   
                   2030:   /* allocate pointers to rows */ 
                   2031:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2032:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2033:   m += NR_END; 
                   2034:   m -= nrl; 
                   2035:   
                   2036:   
                   2037:   /* allocate rows and set pointers to them */ 
                   2038:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2039:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2040:   m[nrl] += NR_END; 
                   2041:   m[nrl] -= ncl; 
                   2042:   
                   2043:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2044:   
                   2045:   /* return pointer to array of pointers to rows */ 
                   2046:   return m; 
                   2047: } 
                   2048: 
                   2049: /****************** free_imatrix *************************/
                   2050: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2051:       int **m;
                   2052:       long nch,ncl,nrh,nrl; 
                   2053:      /* free an int matrix allocated by imatrix() */ 
                   2054: { 
                   2055:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2056:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2057: } 
                   2058: 
                   2059: /******************* matrix *******************************/
                   2060: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2061: {
                   2062:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2063:   double **m;
                   2064: 
                   2065:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2066:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2067:   m += NR_END;
                   2068:   m -= nrl;
                   2069: 
                   2070:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2071:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2072:   m[nrl] += NR_END;
                   2073:   m[nrl] -= ncl;
                   2074: 
                   2075:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2076:   return m;
1.145     brouard  2077:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2078: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2079: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2080:    */
                   2081: }
                   2082: 
                   2083: /*************************free matrix ************************/
                   2084: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2085: {
                   2086:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2087:   free((FREE_ARG)(m+nrl-NR_END));
                   2088: }
                   2089: 
                   2090: /******************* ma3x *******************************/
                   2091: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2092: {
                   2093:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2094:   double ***m;
                   2095: 
                   2096:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2097:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2098:   m += NR_END;
                   2099:   m -= nrl;
                   2100: 
                   2101:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2102:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2103:   m[nrl] += NR_END;
                   2104:   m[nrl] -= ncl;
                   2105: 
                   2106:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2107: 
                   2108:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2109:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2110:   m[nrl][ncl] += NR_END;
                   2111:   m[nrl][ncl] -= nll;
                   2112:   for (j=ncl+1; j<=nch; j++) 
                   2113:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2114:   
                   2115:   for (i=nrl+1; i<=nrh; i++) {
                   2116:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2117:     for (j=ncl+1; j<=nch; j++) 
                   2118:       m[i][j]=m[i][j-1]+nlay;
                   2119:   }
                   2120:   return m; 
                   2121:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2122:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2123:   */
                   2124: }
                   2125: 
                   2126: /*************************free ma3x ************************/
                   2127: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2128: {
                   2129:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2130:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2131:   free((FREE_ARG)(m+nrl-NR_END));
                   2132: }
                   2133: 
                   2134: /*************** function subdirf ***********/
                   2135: char *subdirf(char fileres[])
                   2136: {
                   2137:   /* Caution optionfilefiname is hidden */
                   2138:   strcpy(tmpout,optionfilefiname);
                   2139:   strcat(tmpout,"/"); /* Add to the right */
                   2140:   strcat(tmpout,fileres);
                   2141:   return tmpout;
                   2142: }
                   2143: 
                   2144: /*************** function subdirf2 ***********/
                   2145: char *subdirf2(char fileres[], char *preop)
                   2146: {
1.314     brouard  2147:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2148:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2149:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2150:   /* Caution optionfilefiname is hidden */
                   2151:   strcpy(tmpout,optionfilefiname);
                   2152:   strcat(tmpout,"/");
                   2153:   strcat(tmpout,preop);
                   2154:   strcat(tmpout,fileres);
                   2155:   return tmpout;
                   2156: }
                   2157: 
                   2158: /*************** function subdirf3 ***********/
                   2159: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2160: {
                   2161:   
                   2162:   /* Caution optionfilefiname is hidden */
                   2163:   strcpy(tmpout,optionfilefiname);
                   2164:   strcat(tmpout,"/");
                   2165:   strcat(tmpout,preop);
                   2166:   strcat(tmpout,preop2);
                   2167:   strcat(tmpout,fileres);
                   2168:   return tmpout;
                   2169: }
1.213     brouard  2170:  
                   2171: /*************** function subdirfext ***********/
                   2172: char *subdirfext(char fileres[], char *preop, char *postop)
                   2173: {
                   2174:   
                   2175:   strcpy(tmpout,preop);
                   2176:   strcat(tmpout,fileres);
                   2177:   strcat(tmpout,postop);
                   2178:   return tmpout;
                   2179: }
1.126     brouard  2180: 
1.213     brouard  2181: /*************** function subdirfext3 ***********/
                   2182: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2183: {
                   2184:   
                   2185:   /* Caution optionfilefiname is hidden */
                   2186:   strcpy(tmpout,optionfilefiname);
                   2187:   strcat(tmpout,"/");
                   2188:   strcat(tmpout,preop);
                   2189:   strcat(tmpout,fileres);
                   2190:   strcat(tmpout,postop);
                   2191:   return tmpout;
                   2192: }
                   2193:  
1.162     brouard  2194: char *asc_diff_time(long time_sec, char ascdiff[])
                   2195: {
                   2196:   long sec_left, days, hours, minutes;
                   2197:   days = (time_sec) / (60*60*24);
                   2198:   sec_left = (time_sec) % (60*60*24);
                   2199:   hours = (sec_left) / (60*60) ;
                   2200:   sec_left = (sec_left) %(60*60);
                   2201:   minutes = (sec_left) /60;
                   2202:   sec_left = (sec_left) % (60);
                   2203:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2204:   return ascdiff;
                   2205: }
                   2206: 
1.126     brouard  2207: /***************** f1dim *************************/
                   2208: extern int ncom; 
                   2209: extern double *pcom,*xicom;
                   2210: extern double (*nrfunc)(double []); 
                   2211:  
                   2212: double f1dim(double x) 
                   2213: { 
                   2214:   int j; 
                   2215:   double f;
                   2216:   double *xt; 
                   2217:  
                   2218:   xt=vector(1,ncom); 
                   2219:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2220:   f=(*nrfunc)(xt); 
                   2221:   free_vector(xt,1,ncom); 
                   2222:   return f; 
                   2223: } 
                   2224: 
                   2225: /*****************brent *************************/
                   2226: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2227: {
                   2228:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2229:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2230:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2231:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2232:    * returned function value. 
                   2233:   */
1.126     brouard  2234:   int iter; 
                   2235:   double a,b,d,etemp;
1.159     brouard  2236:   double fu=0,fv,fw,fx;
1.164     brouard  2237:   double ftemp=0.;
1.126     brouard  2238:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2239:   double e=0.0; 
                   2240:  
                   2241:   a=(ax < cx ? ax : cx); 
                   2242:   b=(ax > cx ? ax : cx); 
                   2243:   x=w=v=bx; 
                   2244:   fw=fv=fx=(*f)(x); 
                   2245:   for (iter=1;iter<=ITMAX;iter++) { 
                   2246:     xm=0.5*(a+b); 
                   2247:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2248:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2249:     printf(".");fflush(stdout);
                   2250:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2251: #ifdef DEBUGBRENT
1.126     brouard  2252:     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);
                   2253:     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);
                   2254:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2255: #endif
                   2256:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2257:       *xmin=x; 
                   2258:       return fx; 
                   2259:     } 
                   2260:     ftemp=fu;
                   2261:     if (fabs(e) > tol1) { 
                   2262:       r=(x-w)*(fx-fv); 
                   2263:       q=(x-v)*(fx-fw); 
                   2264:       p=(x-v)*q-(x-w)*r; 
                   2265:       q=2.0*(q-r); 
                   2266:       if (q > 0.0) p = -p; 
                   2267:       q=fabs(q); 
                   2268:       etemp=e; 
                   2269:       e=d; 
                   2270:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2271:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2272:       else { 
1.224     brouard  2273:                                d=p/q; 
                   2274:                                u=x+d; 
                   2275:                                if (u-a < tol2 || b-u < tol2) 
                   2276:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2277:       } 
                   2278:     } else { 
                   2279:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2280:     } 
                   2281:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2282:     fu=(*f)(u); 
                   2283:     if (fu <= fx) { 
                   2284:       if (u >= x) a=x; else b=x; 
                   2285:       SHFT(v,w,x,u) 
1.183     brouard  2286:       SHFT(fv,fw,fx,fu) 
                   2287:     } else { 
                   2288:       if (u < x) a=u; else b=u; 
                   2289:       if (fu <= fw || w == x) { 
1.224     brouard  2290:                                v=w; 
                   2291:                                w=u; 
                   2292:                                fv=fw; 
                   2293:                                fw=fu; 
1.183     brouard  2294:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2295:                                v=u; 
                   2296:                                fv=fu; 
1.183     brouard  2297:       } 
                   2298:     } 
1.126     brouard  2299:   } 
                   2300:   nrerror("Too many iterations in brent"); 
                   2301:   *xmin=x; 
                   2302:   return fx; 
                   2303: } 
                   2304: 
                   2305: /****************** mnbrak ***********************/
                   2306: 
                   2307: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2308:            double (*func)(double)) 
1.183     brouard  2309: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2310: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2311: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2312: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2313:    */
1.126     brouard  2314:   double ulim,u,r,q, dum;
                   2315:   double fu; 
1.187     brouard  2316: 
                   2317:   double scale=10.;
                   2318:   int iterscale=0;
                   2319: 
                   2320:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2321:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2322: 
                   2323: 
                   2324:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2325:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2326:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2327:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2328:   /* } */
                   2329: 
1.126     brouard  2330:   if (*fb > *fa) { 
                   2331:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2332:     SHFT(dum,*fb,*fa,dum) 
                   2333:   } 
1.126     brouard  2334:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2335:   *fc=(*func)(*cx); 
1.183     brouard  2336: #ifdef DEBUG
1.224     brouard  2337:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2338:   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  2339: #endif
1.224     brouard  2340:   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  2341:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2342:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2343:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2344:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2345:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2346:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2347:       fu=(*func)(u); 
1.163     brouard  2348: #ifdef DEBUG
                   2349:       /* f(x)=A(x-u)**2+f(u) */
                   2350:       double A, fparabu; 
                   2351:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2352:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2353:       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);
                   2354:       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  2355:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2356:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2357:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2358:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2359: #endif 
1.184     brouard  2360: #ifdef MNBRAKORIGINAL
1.183     brouard  2361: #else
1.191     brouard  2362: /*       if (fu > *fc) { */
                   2363: /* #ifdef DEBUG */
                   2364: /*       printf("mnbrak4  fu > fc \n"); */
                   2365: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2366: /* #endif */
                   2367: /*     /\* 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 *\\/  *\/ */
                   2368: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2369: /*     dum=u; /\* Shifting c and u *\/ */
                   2370: /*     u = *cx; */
                   2371: /*     *cx = dum; */
                   2372: /*     dum = fu; */
                   2373: /*     fu = *fc; */
                   2374: /*     *fc =dum; */
                   2375: /*       } else { /\* end *\/ */
                   2376: /* #ifdef DEBUG */
                   2377: /*       printf("mnbrak3  fu < fc \n"); */
                   2378: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2379: /* #endif */
                   2380: /*     dum=u; /\* Shifting c and u *\/ */
                   2381: /*     u = *cx; */
                   2382: /*     *cx = dum; */
                   2383: /*     dum = fu; */
                   2384: /*     fu = *fc; */
                   2385: /*     *fc =dum; */
                   2386: /*       } */
1.224     brouard  2387: #ifdef DEBUGMNBRAK
                   2388:                 double A, fparabu; 
                   2389:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2390:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2391:      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);
                   2392:      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  2393: #endif
1.191     brouard  2394:       dum=u; /* Shifting c and u */
                   2395:       u = *cx;
                   2396:       *cx = dum;
                   2397:       dum = fu;
                   2398:       fu = *fc;
                   2399:       *fc =dum;
1.183     brouard  2400: #endif
1.162     brouard  2401:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2402: #ifdef DEBUG
1.224     brouard  2403:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2404:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2405: #endif
1.126     brouard  2406:       fu=(*func)(u); 
                   2407:       if (fu < *fc) { 
1.183     brouard  2408: #ifdef DEBUG
1.224     brouard  2409:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2410:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2411: #endif
                   2412:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2413:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2414: #ifdef DEBUG
                   2415:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2416: #endif
                   2417:       } 
1.162     brouard  2418:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2419: #ifdef DEBUG
1.224     brouard  2420:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2421:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2422: #endif
1.126     brouard  2423:       u=ulim; 
                   2424:       fu=(*func)(u); 
1.183     brouard  2425:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2426: #ifdef DEBUG
1.224     brouard  2427:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2428:       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  2429: #endif
1.126     brouard  2430:       u=(*cx)+GOLD*(*cx-*bx); 
                   2431:       fu=(*func)(u); 
1.224     brouard  2432: #ifdef DEBUG
                   2433:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2434:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2435: #endif
1.183     brouard  2436:     } /* end tests */
1.126     brouard  2437:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2438:     SHFT(*fa,*fb,*fc,fu) 
                   2439: #ifdef DEBUG
1.224     brouard  2440:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2441:       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  2442: #endif
                   2443:   } /* 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  2444: } 
                   2445: 
                   2446: /*************** linmin ************************/
1.162     brouard  2447: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2448: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2449: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2450: the value of func at the returned location p . This is actually all accomplished by calling the
                   2451: routines mnbrak and brent .*/
1.126     brouard  2452: int ncom; 
                   2453: double *pcom,*xicom;
                   2454: double (*nrfunc)(double []); 
                   2455:  
1.224     brouard  2456: #ifdef LINMINORIGINAL
1.126     brouard  2457: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2458: #else
                   2459: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2460: #endif
1.126     brouard  2461: { 
                   2462:   double brent(double ax, double bx, double cx, 
                   2463:               double (*f)(double), double tol, double *xmin); 
                   2464:   double f1dim(double x); 
                   2465:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2466:              double *fc, double (*func)(double)); 
                   2467:   int j; 
                   2468:   double xx,xmin,bx,ax; 
                   2469:   double fx,fb,fa;
1.187     brouard  2470: 
1.203     brouard  2471: #ifdef LINMINORIGINAL
                   2472: #else
                   2473:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2474: #endif
                   2475:   
1.126     brouard  2476:   ncom=n; 
                   2477:   pcom=vector(1,n); 
                   2478:   xicom=vector(1,n); 
                   2479:   nrfunc=func; 
                   2480:   for (j=1;j<=n;j++) { 
                   2481:     pcom[j]=p[j]; 
1.202     brouard  2482:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2483:   } 
1.187     brouard  2484: 
1.203     brouard  2485: #ifdef LINMINORIGINAL
                   2486:   xx=1.;
                   2487: #else
                   2488:   axs=0.0;
                   2489:   xxs=1.;
                   2490:   do{
                   2491:     xx= xxs;
                   2492: #endif
1.187     brouard  2493:     ax=0.;
                   2494:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2495:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2496:     /* 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))   */
                   2497:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2498:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2499:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2500:     /* 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  2501: #ifdef LINMINORIGINAL
                   2502: #else
                   2503:     if (fx != fx){
1.224     brouard  2504:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2505:                        printf("|");
                   2506:                        fprintf(ficlog,"|");
1.203     brouard  2507: #ifdef DEBUGLINMIN
1.224     brouard  2508:                        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  2509: #endif
                   2510:     }
1.224     brouard  2511:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2512: #endif
                   2513:   
1.191     brouard  2514: #ifdef DEBUGLINMIN
                   2515:   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  2516:   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  2517: #endif
1.224     brouard  2518: #ifdef LINMINORIGINAL
                   2519: #else
1.317     brouard  2520:   if(fb == fx){ /* Flat function in the direction */
                   2521:     xmin=xx;
1.224     brouard  2522:     *flat=1;
1.317     brouard  2523:   }else{
1.224     brouard  2524:     *flat=0;
                   2525: #endif
                   2526:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2527:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2528:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2529:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2530:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2531:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2532: #ifdef DEBUG
1.224     brouard  2533:   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);
                   2534:   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);
                   2535: #endif
                   2536: #ifdef LINMINORIGINAL
                   2537: #else
                   2538:                        }
1.126     brouard  2539: #endif
1.191     brouard  2540: #ifdef DEBUGLINMIN
                   2541:   printf("linmin end ");
1.202     brouard  2542:   fprintf(ficlog,"linmin end ");
1.191     brouard  2543: #endif
1.126     brouard  2544:   for (j=1;j<=n;j++) { 
1.203     brouard  2545: #ifdef LINMINORIGINAL
                   2546:     xi[j] *= xmin; 
                   2547: #else
                   2548: #ifdef DEBUGLINMIN
                   2549:     if(xxs <1.0)
                   2550:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2551: #endif
                   2552:     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) */
                   2553: #ifdef DEBUGLINMIN
                   2554:     if(xxs <1.0)
                   2555:       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 );
                   2556: #endif
                   2557: #endif
1.187     brouard  2558:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2559:   } 
1.191     brouard  2560: #ifdef DEBUGLINMIN
1.203     brouard  2561:   printf("\n");
1.191     brouard  2562:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2563:   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  2564:   for (j=1;j<=n;j++) { 
1.202     brouard  2565:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2566:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2567:     if(j % ncovmodel == 0){
1.191     brouard  2568:       printf("\n");
1.202     brouard  2569:       fprintf(ficlog,"\n");
                   2570:     }
1.191     brouard  2571:   }
1.203     brouard  2572: #else
1.191     brouard  2573: #endif
1.126     brouard  2574:   free_vector(xicom,1,n); 
                   2575:   free_vector(pcom,1,n); 
                   2576: } 
                   2577: 
                   2578: 
                   2579: /*************** powell ************************/
1.162     brouard  2580: /*
1.317     brouard  2581: Minimization of a function func of n variables. Input consists in an initial starting point
                   2582: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2583: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2584: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2585: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2586: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2587:  */
1.224     brouard  2588: #ifdef LINMINORIGINAL
                   2589: #else
                   2590:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2591:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2592: #endif
1.126     brouard  2593: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2594:            double (*func)(double [])) 
                   2595: { 
1.224     brouard  2596: #ifdef LINMINORIGINAL
                   2597:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2598:              double (*func)(double [])); 
1.224     brouard  2599: #else 
1.241     brouard  2600:  void linmin(double p[], double xi[], int n, double *fret,
                   2601:             double (*func)(double []),int *flat); 
1.224     brouard  2602: #endif
1.239     brouard  2603:  int i,ibig,j,jk,k; 
1.126     brouard  2604:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2605:   double directest;
1.126     brouard  2606:   double fp,fptt;
                   2607:   double *xits;
                   2608:   int niterf, itmp;
1.349   ! brouard  2609:   int Bigter=0, nBigterf=1;
        !          2610:   
1.126     brouard  2611:   pt=vector(1,n); 
                   2612:   ptt=vector(1,n); 
                   2613:   xit=vector(1,n); 
                   2614:   xits=vector(1,n); 
                   2615:   *fret=(*func)(p); 
                   2616:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2617:   rcurr_time = time(NULL);
                   2618:   fp=(*fret); /* Initialisation */
1.126     brouard  2619:   for (*iter=1;;++(*iter)) { 
                   2620:     ibig=0; 
                   2621:     del=0.0; 
1.157     brouard  2622:     rlast_time=rcurr_time;
1.349   ! brouard  2623:     rlast_btime=rcurr_time;
1.157     brouard  2624:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2625:     rcurr_time = time(NULL);  
                   2626:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2627:     /* 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); */
                   2628:     /* fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); */
1.349   ! brouard  2629:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
        !          2630:     printf("\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
        !          2631:     fprintf(ficlog,"\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
        !          2632:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2633:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2634:     for (i=1;i<=n;i++) {
1.126     brouard  2635:       fprintf(ficrespow," %.12lf", p[i]);
                   2636:     }
1.239     brouard  2637:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2638:     printf("\n#model=  1      +     age ");
                   2639:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2640:     if(nagesqr==1){
1.241     brouard  2641:        printf("  + age*age  ");
                   2642:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2643:     }
                   2644:     for(j=1;j <=ncovmodel-2;j++){
                   2645:       if(Typevar[j]==0) {
                   2646:        printf("  +      V%d  ",Tvar[j]);
                   2647:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2648:       }else if(Typevar[j]==1) {
                   2649:        printf("  +    V%d*age ",Tvar[j]);
                   2650:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2651:       }else if(Typevar[j]==2) {
                   2652:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2653:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349   ! brouard  2654:       }else if(Typevar[j]==3) {
        !          2655:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          2656:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2657:       }
                   2658:     }
1.126     brouard  2659:     printf("\n");
1.239     brouard  2660: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2661: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2662:     fprintf(ficlog,"\n");
1.239     brouard  2663:     for(i=1,jk=1; i <=nlstate; i++){
                   2664:       for(k=1; k <=(nlstate+ndeath); k++){
                   2665:        if (k != i) {
                   2666:          printf("%d%d ",i,k);
                   2667:          fprintf(ficlog,"%d%d ",i,k);
                   2668:          for(j=1; j <=ncovmodel; j++){
                   2669:            printf("%12.7f ",p[jk]);
                   2670:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2671:            jk++; 
                   2672:          }
                   2673:          printf("\n");
                   2674:          fprintf(ficlog,"\n");
                   2675:        }
                   2676:       }
                   2677:     }
1.241     brouard  2678:     if(*iter <=3 && *iter >1){
1.157     brouard  2679:       tml = *localtime(&rcurr_time);
                   2680:       strcpy(strcurr,asctime(&tml));
                   2681:       rforecast_time=rcurr_time; 
1.126     brouard  2682:       itmp = strlen(strcurr);
                   2683:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2684:        strcurr[itmp-1]='\0';
1.162     brouard  2685:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2686:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349   ! brouard  2687:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
        !          2688:        niterf=nBigterf*ncovmodel;
        !          2689:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2690:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2691:        forecast_time = *localtime(&rforecast_time);
                   2692:        strcpy(strfor,asctime(&forecast_time));
                   2693:        itmp = strlen(strfor);
                   2694:        if(strfor[itmp-1]=='\n')
                   2695:          strfor[itmp-1]='\0';
1.349   ! brouard  2696:        printf("   - if your program needs %d BIG iterations (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
        !          2697:        fprintf(ficlog,"   - if your program needs %d BIG iterations  (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2698:       }
                   2699:     }
1.187     brouard  2700:     for (i=1;i<=n;i++) { /* For each direction i */
                   2701:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2702:       fptt=(*fret); 
                   2703: #ifdef DEBUG
1.203     brouard  2704:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2705:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2706: #endif
1.203     brouard  2707:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2708:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2709: #ifdef LINMINORIGINAL
1.188     brouard  2710:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2711: #else
                   2712:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2713:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2714: #endif
                   2715:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2716:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2717:                                /* because that direction will be replaced unless the gain del is small */
                   2718:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2719:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2720:                                /* with the new direction. */
                   2721:                                del=fabs(fptt-(*fret)); 
                   2722:                                ibig=i; 
1.126     brouard  2723:       } 
                   2724: #ifdef DEBUG
                   2725:       printf("%d %.12e",i,(*fret));
                   2726:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2727:       for (j=1;j<=n;j++) {
1.224     brouard  2728:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2729:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2730:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2731:       }
                   2732:       for(j=1;j<=n;j++) {
1.225     brouard  2733:                                printf(" p(%d)=%.12e",j,p[j]);
                   2734:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2735:       }
                   2736:       printf("\n");
                   2737:       fprintf(ficlog,"\n");
                   2738: #endif
1.187     brouard  2739:     } /* end loop on each direction i */
                   2740:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2741:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2742:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2743:     for(j=1;j<=n;j++) {
                   2744:       if(flatdir[j] >0){
                   2745:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2746:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2747:       }
1.319     brouard  2748:       /* printf("\n"); */
                   2749:       /* fprintf(ficlog,"\n"); */
                   2750:     }
1.243     brouard  2751:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2752:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2753:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2754:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2755:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2756:       /* decreased of more than 3.84  */
                   2757:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2758:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2759:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2760:                        
1.188     brouard  2761:       /* Starting the program with initial values given by a former maximization will simply change */
                   2762:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2763:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2764:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2765: #ifdef DEBUG
                   2766:       int k[2],l;
                   2767:       k[0]=1;
                   2768:       k[1]=-1;
                   2769:       printf("Max: %.12e",(*func)(p));
                   2770:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2771:       for (j=1;j<=n;j++) {
                   2772:        printf(" %.12e",p[j]);
                   2773:        fprintf(ficlog," %.12e",p[j]);
                   2774:       }
                   2775:       printf("\n");
                   2776:       fprintf(ficlog,"\n");
                   2777:       for(l=0;l<=1;l++) {
                   2778:        for (j=1;j<=n;j++) {
                   2779:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2780:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2781:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2782:        }
                   2783:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2784:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2785:       }
                   2786: #endif
                   2787: 
                   2788:       free_vector(xit,1,n); 
                   2789:       free_vector(xits,1,n); 
                   2790:       free_vector(ptt,1,n); 
                   2791:       free_vector(pt,1,n); 
                   2792:       return; 
1.192     brouard  2793:     } /* enough precision */ 
1.240     brouard  2794:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2795:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2796:       ptt[j]=2.0*p[j]-pt[j]; 
                   2797:       xit[j]=p[j]-pt[j]; 
                   2798:       pt[j]=p[j]; 
                   2799:     } 
1.181     brouard  2800:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2801: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2802:                if (*iter <=4) {
1.225     brouard  2803: #else
                   2804: #endif
1.224     brouard  2805: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2806: #else
1.161     brouard  2807:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2808: #endif
1.162     brouard  2809:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2810:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2811:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2812:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2813:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2814:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2815:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2816:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2817:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2818:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2819:       /* mu² and del² are equal when f3=f1 */
                   2820:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2821:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2822:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2823:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2824: #ifdef NRCORIGINAL
                   2825:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2826: #else
                   2827:       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  2828:       t= t- del*SQR(fp-fptt);
1.183     brouard  2829: #endif
1.202     brouard  2830:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2831: #ifdef DEBUG
1.181     brouard  2832:       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);
                   2833:       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  2834:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2835:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2836:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2837:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2838:       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);
                   2839:       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);
                   2840: #endif
1.183     brouard  2841: #ifdef POWELLORIGINAL
                   2842:       if (t < 0.0) { /* Then we use it for new direction */
                   2843: #else
1.182     brouard  2844:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2845:                                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  2846:         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  2847:         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  2848:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2849:       } 
1.181     brouard  2850:       if (directest < 0.0) { /* Then we use it for new direction */
                   2851: #endif
1.191     brouard  2852: #ifdef DEBUGLINMIN
1.234     brouard  2853:        printf("Before linmin in direction P%d-P0\n",n);
                   2854:        for (j=1;j<=n;j++) {
                   2855:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2856:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2857:          if(j % ncovmodel == 0){
                   2858:            printf("\n");
                   2859:            fprintf(ficlog,"\n");
                   2860:          }
                   2861:        }
1.224     brouard  2862: #endif
                   2863: #ifdef LINMINORIGINAL
1.234     brouard  2864:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2865: #else
1.234     brouard  2866:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2867:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2868: #endif
1.234     brouard  2869:        
1.191     brouard  2870: #ifdef DEBUGLINMIN
1.234     brouard  2871:        for (j=1;j<=n;j++) { 
                   2872:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2873:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2874:          if(j % ncovmodel == 0){
                   2875:            printf("\n");
                   2876:            fprintf(ficlog,"\n");
                   2877:          }
                   2878:        }
1.224     brouard  2879: #endif
1.234     brouard  2880:        for (j=1;j<=n;j++) { 
                   2881:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2882:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2883:        }
1.224     brouard  2884: #ifdef LINMINORIGINAL
                   2885: #else
1.234     brouard  2886:        for (j=1, flatd=0;j<=n;j++) {
                   2887:          if(flatdir[j]>0)
                   2888:            flatd++;
                   2889:        }
                   2890:        if(flatd >0){
1.255     brouard  2891:          printf("%d flat directions: ",flatd);
                   2892:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2893:          for (j=1;j<=n;j++) { 
                   2894:            if(flatdir[j]>0){
                   2895:              printf("%d ",j);
                   2896:              fprintf(ficlog,"%d ",j);
                   2897:            }
                   2898:          }
                   2899:          printf("\n");
                   2900:          fprintf(ficlog,"\n");
1.319     brouard  2901: #ifdef FLATSUP
                   2902:           free_vector(xit,1,n); 
                   2903:           free_vector(xits,1,n); 
                   2904:           free_vector(ptt,1,n); 
                   2905:           free_vector(pt,1,n); 
                   2906:           return;
                   2907: #endif
1.234     brouard  2908:        }
1.191     brouard  2909: #endif
1.234     brouard  2910:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2911:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2912:        
1.126     brouard  2913: #ifdef DEBUG
1.234     brouard  2914:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2915:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2916:        for(j=1;j<=n;j++){
                   2917:          printf(" %lf",xit[j]);
                   2918:          fprintf(ficlog," %lf",xit[j]);
                   2919:        }
                   2920:        printf("\n");
                   2921:        fprintf(ficlog,"\n");
1.126     brouard  2922: #endif
1.192     brouard  2923:       } /* end of t or directest negative */
1.224     brouard  2924: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2925: #else
1.234     brouard  2926:       } /* end if (fptt < fp)  */
1.192     brouard  2927: #endif
1.225     brouard  2928: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2929:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2930: #else
1.224     brouard  2931: #endif
1.234     brouard  2932:                } /* loop iteration */ 
1.126     brouard  2933: } 
1.234     brouard  2934:   
1.126     brouard  2935: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2936:   
1.235     brouard  2937:   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  2938:   {
1.338     brouard  2939:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2940:      *   (and selected quantitative values in nres)
                   2941:      *  by left multiplying the unit
                   2942:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2943:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2944:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2945:      * or prevalence in state 1, prevalence in state 2, 0
                   2946:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2947:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2948:      * Output is prlim.
                   2949:      * Initial matrix pimij 
                   2950:      */
1.206     brouard  2951:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2952:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2953:   /*  0,                   0                  , 1} */
                   2954:   /*
                   2955:    * and after some iteration: */
                   2956:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2957:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2958:   /*  0,                   0                  , 1} */
                   2959:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2960:   /* {0.51571254859325999, 0.4842874514067399, */
                   2961:   /*  0.51326036147820708, 0.48673963852179264} */
                   2962:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2963:     
1.332     brouard  2964:     int i, ii,j,k, k1;
1.209     brouard  2965:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2966:   /* double **matprod2(); */ /* test */
1.218     brouard  2967:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2968:   double **newm;
1.209     brouard  2969:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2970:   int ncvloop=0;
1.288     brouard  2971:   int first=0;
1.169     brouard  2972:   
1.209     brouard  2973:   min=vector(1,nlstate);
                   2974:   max=vector(1,nlstate);
                   2975:   meandiff=vector(1,nlstate);
                   2976: 
1.218     brouard  2977:        /* Starting with matrix unity */
1.126     brouard  2978:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2979:     for (j=1;j<=nlstate+ndeath;j++){
                   2980:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2981:     }
1.169     brouard  2982:   
                   2983:   cov[1]=1.;
                   2984:   
                   2985:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2986:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2987:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2988:     ncvloop++;
1.126     brouard  2989:     newm=savm;
                   2990:     /* Covariates have to be included here again */
1.138     brouard  2991:     cov[2]=agefin;
1.319     brouard  2992:      if(nagesqr==1){
                   2993:       cov[3]= agefin*agefin;
                   2994:      }
1.332     brouard  2995:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2996:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2997:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349   ! brouard  2998:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  2999:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3000:        }else{
                   3001:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3002:        }
                   3003:      }/* End of loop on model equation */
                   3004:      
                   3005: /* Start of old code (replaced by a loop on position in the model equation */
                   3006:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3007:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3008:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3009:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3010:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3011:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3012:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3013:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3014:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3015:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3016:     /*    *nsd=3                              (1)  (2)           (3) */
                   3017:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3018:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3019:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3020:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3021:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3022:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3023:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3024:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3025:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3026:     /*    *TvarsDpType */
                   3027:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3028:     /*    * nsd=1              (1)           (2) */
                   3029:     /*    *TvarsD[nsd]          3             2 */
                   3030:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3031:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3032:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3033:     /*    *\/ */
                   3034:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3035:     /*   /\* 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)); *\/ */
                   3036:     /* } */
                   3037:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3038:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3039:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3040:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3041:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3042:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3043:     /*   /\* 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]); *\/ */
                   3044:     /* } */
                   3045:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3046:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3047:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3048:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3049:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3050:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3051:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3052:     /*   } */
                   3053:     /*   /\* 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]); *\/ */
                   3054:     /* } */
                   3055:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3056:     /*   /\* 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]); *\/ */
                   3057:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3058:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3059:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3060:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3061:     /*         }else{ */
                   3062:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3063:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3064:     /*         } */
                   3065:     /*   }else{ */
                   3066:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3067:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3068:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3069:     /*         }else{ */
                   3070:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3071:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3072:     /*         } */
                   3073:     /*   } */
                   3074:     /* } /\* End product without age *\/ */
                   3075: /* ENd of old code */
1.138     brouard  3076:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3077:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3078:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3079:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3080:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3081:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3082:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3083:     
1.126     brouard  3084:     savm=oldm;
                   3085:     oldm=newm;
1.209     brouard  3086: 
                   3087:     for(j=1; j<=nlstate; j++){
                   3088:       max[j]=0.;
                   3089:       min[j]=1.;
                   3090:     }
                   3091:     for(i=1;i<=nlstate;i++){
                   3092:       sumnew=0;
                   3093:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3094:       for(j=1; j<=nlstate; j++){ 
                   3095:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3096:        max[j]=FMAX(max[j],prlim[i][j]);
                   3097:        min[j]=FMIN(min[j],prlim[i][j]);
                   3098:       }
                   3099:     }
                   3100: 
1.126     brouard  3101:     maxmax=0.;
1.209     brouard  3102:     for(j=1; j<=nlstate; j++){
                   3103:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3104:       maxmax=FMAX(maxmax,meandiff[j]);
                   3105:       /* 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  3106:     } /* j loop */
1.203     brouard  3107:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3108:     /* 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  3109:     if(maxmax < ftolpl){
1.209     brouard  3110:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3111:       free_vector(min,1,nlstate);
                   3112:       free_vector(max,1,nlstate);
                   3113:       free_vector(meandiff,1,nlstate);
1.126     brouard  3114:       return prlim;
                   3115:     }
1.288     brouard  3116:   } /* agefin loop */
1.208     brouard  3117:     /* After some age loop it doesn't converge */
1.288     brouard  3118:   if(!first){
                   3119:     first=1;
                   3120:     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  3121:     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);
                   3122:   }else if (first >=1 && first <10){
                   3123:     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);
                   3124:     first++;
                   3125:   }else if (first ==10){
                   3126:     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);
                   3127:     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");
                   3128:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3129:     first++;
1.288     brouard  3130:   }
                   3131: 
1.209     brouard  3132:   /* 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); */
                   3133:   free_vector(min,1,nlstate);
                   3134:   free_vector(max,1,nlstate);
                   3135:   free_vector(meandiff,1,nlstate);
1.208     brouard  3136:   
1.169     brouard  3137:   return prlim; /* should not reach here */
1.126     brouard  3138: }
                   3139: 
1.217     brouard  3140: 
                   3141:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3142: 
1.218     brouard  3143:  /* 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) */
                   3144:  /* 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  3145:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3146: {
1.264     brouard  3147:   /* 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  3148:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3149:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3150:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3151:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3152:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3153:   /* Initial matrix pimij */
                   3154:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3155:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3156:   /*  0,                   0                  , 1} */
                   3157:   /*
                   3158:    * and after some iteration: */
                   3159:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3160:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3161:   /*  0,                   0                  , 1} */
                   3162:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3163:   /* {0.51571254859325999, 0.4842874514067399, */
                   3164:   /*  0.51326036147820708, 0.48673963852179264} */
                   3165:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3166: 
1.332     brouard  3167:   int i, ii,j,k, k1;
1.247     brouard  3168:   int first=0;
1.217     brouard  3169:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3170:   /* double **matprod2(); */ /* test */
                   3171:   double **out, cov[NCOVMAX+1], **bmij();
                   3172:   double **newm;
1.218     brouard  3173:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3174:   double        **oldm, **savm;  /* for use */
                   3175: 
1.217     brouard  3176:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3177:   int ncvloop=0;
                   3178:   
                   3179:   min=vector(1,nlstate);
                   3180:   max=vector(1,nlstate);
                   3181:   meandiff=vector(1,nlstate);
                   3182: 
1.266     brouard  3183:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3184:   oldm=oldms; savm=savms;
                   3185:   
                   3186:   /* Starting with matrix unity */
                   3187:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3188:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3189:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3190:     }
                   3191:   
                   3192:   cov[1]=1.;
                   3193:   
                   3194:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3195:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3196:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3197:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3198:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3199:     ncvloop++;
1.218     brouard  3200:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3201:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3202:     /* Covariates have to be included here again */
                   3203:     cov[2]=agefin;
1.319     brouard  3204:     if(nagesqr==1){
1.217     brouard  3205:       cov[3]= agefin*agefin;;
1.319     brouard  3206:     }
1.332     brouard  3207:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349   ! brouard  3208:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3209:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3210:       }else{
1.332     brouard  3211:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3212:       }
1.332     brouard  3213:     }/* End of loop on model equation */
                   3214: 
                   3215: /* Old code */ 
                   3216: 
                   3217:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3218:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3219:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3220:     /*   /\* 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)); *\/ */
                   3221:     /* } */
                   3222:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3223:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3224:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3225:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3226:     /* /\* } *\/ */
                   3227:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3228:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3229:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3230:     /*   /\* 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]); *\/ */
                   3231:     /* } */
                   3232:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3233:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3234:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3235:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3236:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3237:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3238:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3239:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3240:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3241:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3242:     /*   } */
                   3243:     /*   /\* 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]); *\/ */
                   3244:     /* } */
                   3245:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3246:     /*   /\* 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]); *\/ */
                   3247:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3248:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3249:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3250:     /*         }else{ */
                   3251:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3252:     /*         } */
                   3253:     /*   }else{ */
                   3254:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3255:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3256:     /*         }else{ */
                   3257:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3258:     /*         } */
                   3259:     /*   } */
                   3260:     /* } */
1.217     brouard  3261:     
                   3262:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3263:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3264:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3265:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3266:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3267:                /* ij should be linked to the correct index of cov */
                   3268:                /* age and covariate values ij are in 'cov', but we need to pass
                   3269:                 * ij for the observed prevalence at age and status and covariate
                   3270:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3271:                 */
                   3272:     /* 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 *\/ */
                   3273:     /* 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 *\/ */
                   3274:     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  3275:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3276:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3277:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3278:     /*         printf("%d newm= ",i); */
                   3279:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3280:     /*           printf("%f ",newm[i][j]); */
                   3281:     /*         } */
                   3282:     /*         printf("oldm * "); */
                   3283:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3284:     /*           printf("%f ",oldm[i][j]); */
                   3285:     /*         } */
1.268     brouard  3286:     /*         printf(" bmmij "); */
1.266     brouard  3287:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3288:     /*           printf("%f ",pmmij[i][j]); */
                   3289:     /*         } */
                   3290:     /*         printf("\n"); */
                   3291:     /*   } */
                   3292:     /* } */
1.217     brouard  3293:     savm=oldm;
                   3294:     oldm=newm;
1.266     brouard  3295: 
1.217     brouard  3296:     for(j=1; j<=nlstate; j++){
                   3297:       max[j]=0.;
                   3298:       min[j]=1.;
                   3299:     }
                   3300:     for(j=1; j<=nlstate; j++){ 
                   3301:       for(i=1;i<=nlstate;i++){
1.234     brouard  3302:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3303:        bprlim[i][j]= newm[i][j];
                   3304:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3305:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3306:       }
                   3307:     }
1.218     brouard  3308:                
1.217     brouard  3309:     maxmax=0.;
                   3310:     for(i=1; i<=nlstate; i++){
1.318     brouard  3311:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3312:       maxmax=FMAX(maxmax,meandiff[i]);
                   3313:       /* 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  3314:     } /* i loop */
1.217     brouard  3315:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3316:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3317:     if(maxmax < ftolpl){
1.220     brouard  3318:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3319:       free_vector(min,1,nlstate);
                   3320:       free_vector(max,1,nlstate);
                   3321:       free_vector(meandiff,1,nlstate);
                   3322:       return bprlim;
                   3323:     }
1.288     brouard  3324:   } /* agefin loop */
1.217     brouard  3325:     /* After some age loop it doesn't converge */
1.288     brouard  3326:   if(!first){
1.247     brouard  3327:     first=1;
                   3328:     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\
                   3329: 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);
                   3330:   }
                   3331:   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  3332: 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);
                   3333:   /* 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); */
                   3334:   free_vector(min,1,nlstate);
                   3335:   free_vector(max,1,nlstate);
                   3336:   free_vector(meandiff,1,nlstate);
                   3337:   
                   3338:   return bprlim; /* should not reach here */
                   3339: }
                   3340: 
1.126     brouard  3341: /*************** transition probabilities ***************/ 
                   3342: 
                   3343: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3344: {
1.138     brouard  3345:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3346:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3347:      model to the ncovmodel covariates (including constant and age).
                   3348:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3349:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3350:      ncth covariate in the global vector x is given by the formula:
                   3351:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3352:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3353:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3354:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3355:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3356:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3357:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3358:   */
                   3359:   double s1, lnpijopii;
1.126     brouard  3360:   /*double t34;*/
1.164     brouard  3361:   int i,j, nc, ii, jj;
1.126     brouard  3362: 
1.223     brouard  3363:   for(i=1; i<= nlstate; i++){
                   3364:     for(j=1; j<i;j++){
                   3365:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3366:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3367:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3368:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3369:       }
                   3370:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3371:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3372:     }
                   3373:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3374:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3375:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3376:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3377:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3378:       }
                   3379:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3380:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3381:     }
                   3382:   }
1.218     brouard  3383:   
1.223     brouard  3384:   for(i=1; i<= nlstate; i++){
                   3385:     s1=0;
                   3386:     for(j=1; j<i; j++){
1.339     brouard  3387:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3388:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3389:     }
                   3390:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3391:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3392:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3393:     }
                   3394:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3395:     ps[i][i]=1./(s1+1.);
                   3396:     /* Computing other pijs */
                   3397:     for(j=1; j<i; j++)
1.325     brouard  3398:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3399:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3400:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3401:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3402:   } /* end i */
1.218     brouard  3403:   
1.223     brouard  3404:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3405:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3406:       ps[ii][jj]=0;
                   3407:       ps[ii][ii]=1;
                   3408:     }
                   3409:   }
1.294     brouard  3410: 
                   3411: 
1.223     brouard  3412:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3413:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3414:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3415:   /*   } */
                   3416:   /*   printf("\n "); */
                   3417:   /* } */
                   3418:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3419:   /*
                   3420:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3421:                goto end;*/
1.266     brouard  3422:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3423: }
                   3424: 
1.218     brouard  3425: /*************** backward transition probabilities ***************/ 
                   3426: 
                   3427:  /* 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 ) */
                   3428: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3429:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3430: {
1.302     brouard  3431:   /* 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  3432:    * 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  3433:    */
1.218     brouard  3434:   int i, ii, j,k;
1.222     brouard  3435:   
                   3436:   double **out, **pmij();
                   3437:   double sumnew=0.;
1.218     brouard  3438:   double agefin;
1.292     brouard  3439:   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  3440:   double **dnewm, **dsavm, **doldm;
                   3441:   double **bbmij;
                   3442:   
1.218     brouard  3443:   doldm=ddoldms; /* global pointers */
1.222     brouard  3444:   dnewm=ddnewms;
                   3445:   dsavm=ddsavms;
1.318     brouard  3446: 
                   3447:   /* Debug */
                   3448:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3449:   agefin=cov[2];
1.268     brouard  3450:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3451:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3452:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3453:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3454: 
                   3455:   /* P_x */
1.325     brouard  3456:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3457:   /* outputs pmmij which is a stochastic matrix in row */
                   3458: 
                   3459:   /* Diag(w_x) */
1.292     brouard  3460:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3461:   sumnew=0.;
1.269     brouard  3462:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3463:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3464:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3465:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3466:   }
                   3467:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3468:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3469:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3470:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3471:     }
                   3472:   }else{
                   3473:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3474:       for (j=1;j<=nlstate+ndeath;j++)
                   3475:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3476:     }
                   3477:     /* if(sumnew <0.9){ */
                   3478:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3479:     /* } */
                   3480:   }
                   3481:   k3=0.0;  /* We put the last diagonal to 0 */
                   3482:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3483:       doldm[ii][ii]= k3;
                   3484:   }
                   3485:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3486:   
1.292     brouard  3487:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3488:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3489: 
1.292     brouard  3490:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3491:   /* 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  3492:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3493:     sumnew=0.;
1.222     brouard  3494:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3495:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3496:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3497:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3498:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3499:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3500:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3501:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3502:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3503:        /* }else */
1.268     brouard  3504:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3505:     } /*End ii */
                   3506:   } /* 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 */
                   3507: 
1.292     brouard  3508:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3509:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3510:   /* end bmij */
1.266     brouard  3511:   return ps; /*pointer is unchanged */
1.218     brouard  3512: }
1.217     brouard  3513: /*************** transition probabilities ***************/ 
                   3514: 
1.218     brouard  3515: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3516: {
                   3517:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3518:      computes the probability to be observed in state j being in state i by appying the
                   3519:      model to the ncovmodel covariates (including constant and age).
                   3520:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3521:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3522:      ncth covariate in the global vector x is given by the formula:
                   3523:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3524:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3525:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3526:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3527:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3528:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3529:   */
                   3530:   double s1, lnpijopii;
                   3531:   /*double t34;*/
                   3532:   int i,j, nc, ii, jj;
                   3533: 
1.234     brouard  3534:   for(i=1; i<= nlstate; i++){
                   3535:     for(j=1; j<i;j++){
                   3536:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3537:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3538:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3539:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3540:       }
                   3541:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3542:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3543:     }
                   3544:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3545:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3546:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3547:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3548:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3549:       }
                   3550:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3551:     }
                   3552:   }
                   3553:   
                   3554:   for(i=1; i<= nlstate; i++){
                   3555:     s1=0;
                   3556:     for(j=1; j<i; j++){
                   3557:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3558:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3559:     }
                   3560:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3561:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3562:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3563:     }
                   3564:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3565:     ps[i][i]=1./(s1+1.);
                   3566:     /* Computing other pijs */
                   3567:     for(j=1; j<i; j++)
                   3568:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3569:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3570:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3571:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3572:   } /* end i */
                   3573:   
                   3574:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3575:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3576:       ps[ii][jj]=0;
                   3577:       ps[ii][ii]=1;
                   3578:     }
                   3579:   }
1.296     brouard  3580:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3581:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3582:     s1=0.;
                   3583:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3584:       s1+=ps[ii][jj];
                   3585:     }
                   3586:     for(ii=1; ii<= nlstate; ii++){
                   3587:       ps[ii][jj]=ps[ii][jj]/s1;
                   3588:     }
                   3589:   }
                   3590:   /* Transposition */
                   3591:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3592:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3593:       s1=ps[ii][jj];
                   3594:       ps[ii][jj]=ps[jj][ii];
                   3595:       ps[jj][ii]=s1;
                   3596:     }
                   3597:   }
                   3598:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3599:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3600:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3601:   /*   } */
                   3602:   /*   printf("\n "); */
                   3603:   /* } */
                   3604:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3605:   /*
                   3606:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3607:     goto end;*/
                   3608:   return ps;
1.217     brouard  3609: }
                   3610: 
                   3611: 
1.126     brouard  3612: /**************** Product of 2 matrices ******************/
                   3613: 
1.145     brouard  3614: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3615: {
                   3616:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3617:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3618:   /* in, b, out are matrice of pointers which should have been initialized 
                   3619:      before: only the contents of out is modified. The function returns
                   3620:      a pointer to pointers identical to out */
1.145     brouard  3621:   int i, j, k;
1.126     brouard  3622:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3623:     for(k=ncolol; k<=ncoloh; k++){
                   3624:       out[i][k]=0.;
                   3625:       for(j=ncl; j<=nch; j++)
                   3626:        out[i][k] +=in[i][j]*b[j][k];
                   3627:     }
1.126     brouard  3628:   return out;
                   3629: }
                   3630: 
                   3631: 
                   3632: /************* Higher Matrix Product ***************/
                   3633: 
1.235     brouard  3634: 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  3635: {
1.336     brouard  3636:   /* Already optimized with precov.
                   3637:      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  3638:      'nhstepm*hstepm*stepm' months (i.e. until
                   3639:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3640:      nhstepm*hstepm matrices. 
                   3641:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3642:      (typically every 2 years instead of every month which is too big 
                   3643:      for the memory).
                   3644:      Model is determined by parameters x and covariates have to be 
                   3645:      included manually here. 
                   3646: 
                   3647:      */
                   3648: 
1.330     brouard  3649:   int i, j, d, h, k, k1;
1.131     brouard  3650:   double **out, cov[NCOVMAX+1];
1.126     brouard  3651:   double **newm;
1.187     brouard  3652:   double agexact;
1.214     brouard  3653:   double agebegin, ageend;
1.126     brouard  3654: 
                   3655:   /* Hstepm could be zero and should return the unit matrix */
                   3656:   for (i=1;i<=nlstate+ndeath;i++)
                   3657:     for (j=1;j<=nlstate+ndeath;j++){
                   3658:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3659:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3660:     }
                   3661:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3662:   for(h=1; h <=nhstepm; h++){
                   3663:     for(d=1; d <=hstepm; d++){
                   3664:       newm=savm;
                   3665:       /* Covariates have to be included here again */
                   3666:       cov[1]=1.;
1.214     brouard  3667:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3668:       cov[2]=agexact;
1.319     brouard  3669:       if(nagesqr==1){
1.227     brouard  3670:        cov[3]= agexact*agexact;
1.319     brouard  3671:       }
1.330     brouard  3672:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3673:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3674:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349   ! brouard  3675:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3676:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3677:        }else{
                   3678:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3679:        }
                   3680:       }/* End of loop on model equation */
                   3681:        /* Old code */ 
                   3682: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3683: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3684: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3685: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3686: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3687: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3688: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3689: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3690: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3691: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3692: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3693: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3694: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3695: /*       /\* 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]])); *\/ */
                   3696: /*       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); */
                   3697: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3698: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3699: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3700: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3701: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3702: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3703: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3704: /*       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]]); */
                   3705: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3706: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3707: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3708: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3709: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3710: /*       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]); */
                   3711: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3712: 
                   3713: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3714: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3715: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3716: /*       /\* *\/ */
1.330     brouard  3717: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3718: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3719: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3720: /* /\*cptcovage=2                   1               2      *\/ */
                   3721: /* /\*Tage[k]=                      5               8      *\/  */
                   3722: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3723: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3724: /*       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]]); */
                   3725: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3726: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3727: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3728: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3729: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3730: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3731: /*       /\*   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); *\/ */
                   3732: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3733: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3734: /*       /\* } *\/ */
                   3735: /*       /\* 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]); *\/ */
                   3736: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3737: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3738: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3739: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3740: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3741: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3742: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3743: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3744: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3745:          
1.332     brouard  3746: /*       /\* 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])]); *\/ */
                   3747: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3748: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3749: /*       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]]); */
                   3750: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3751: 
                   3752: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3753: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3754: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3755: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3756: /*           /\* 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]])]; *\/ */
                   3757: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3758: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3759: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3760: /*       /\*   } *\/ */
                   3761: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3762: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3763: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3764: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3765: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3766: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3767: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3768: /*       /\*   } *\/ */
                   3769: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3770: /*     }/\*end of products *\/ */
                   3771:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3772:       /* for (k=1; k<=cptcovn;k++)  */
                   3773:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3774:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3775:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3776:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3777:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3778:       
                   3779:       
1.126     brouard  3780:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3781:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3782:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3783:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3784:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3785:       /* if((int)age == 70){ */
                   3786:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3787:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3788:       /*         printf("%d pmmij ",i); */
                   3789:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3790:       /*           printf("%f ",pmmij[i][j]); */
                   3791:       /*         } */
                   3792:       /*         printf(" oldm "); */
                   3793:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3794:       /*           printf("%f ",oldm[i][j]); */
                   3795:       /*         } */
                   3796:       /*         printf("\n"); */
                   3797:       /*       } */
                   3798:       /* } */
1.126     brouard  3799:       savm=oldm;
                   3800:       oldm=newm;
                   3801:     }
                   3802:     for(i=1; i<=nlstate+ndeath; i++)
                   3803:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3804:        po[i][j][h]=newm[i][j];
                   3805:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3806:       }
1.128     brouard  3807:     /*printf("h=%d ",h);*/
1.126     brouard  3808:   } /* end h */
1.267     brouard  3809:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3810:   return po;
                   3811: }
                   3812: 
1.217     brouard  3813: /************* Higher Back Matrix Product ***************/
1.218     brouard  3814: /* 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  3815: 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  3816: {
1.332     brouard  3817:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3818:      computes the transition matrix starting at age 'age' over
1.217     brouard  3819:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3820:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3821:      nhstepm*hstepm matrices.
                   3822:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3823:      (typically every 2 years instead of every month which is too big
1.217     brouard  3824:      for the memory).
1.218     brouard  3825:      Model is determined by parameters x and covariates have to be
1.266     brouard  3826:      included manually here. Then we use a call to bmij(x and cov)
                   3827:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3828:   */
1.217     brouard  3829: 
1.332     brouard  3830:   int i, j, d, h, k, k1;
1.266     brouard  3831:   double **out, cov[NCOVMAX+1], **bmij();
                   3832:   double **newm, ***newmm;
1.217     brouard  3833:   double agexact;
                   3834:   double agebegin, ageend;
1.222     brouard  3835:   double **oldm, **savm;
1.217     brouard  3836: 
1.266     brouard  3837:   newmm=po; /* To be saved */
                   3838:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3839:   /* Hstepm could be zero and should return the unit matrix */
                   3840:   for (i=1;i<=nlstate+ndeath;i++)
                   3841:     for (j=1;j<=nlstate+ndeath;j++){
                   3842:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3843:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3844:     }
                   3845:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3846:   for(h=1; h <=nhstepm; h++){
                   3847:     for(d=1; d <=hstepm; d++){
                   3848:       newm=savm;
                   3849:       /* Covariates have to be included here again */
                   3850:       cov[1]=1.;
1.271     brouard  3851:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3852:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3853:         /* Debug */
                   3854:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3855:       cov[2]=agexact;
1.332     brouard  3856:       if(nagesqr==1){
1.222     brouard  3857:        cov[3]= agexact*agexact;
1.332     brouard  3858:       }
                   3859:       /** New code */
                   3860:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349   ! brouard  3861:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3862:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3863:        }else{
1.332     brouard  3864:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3865:        }
1.332     brouard  3866:       }/* End of loop on model equation */
                   3867:       /** End of new code */
                   3868:   /** This was old code */
                   3869:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3870:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3871:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3872:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3873:       /*   /\* 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)); *\/ */
                   3874:       /* } */
                   3875:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3876:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3877:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3878:       /*       /\* 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]); *\/ */
                   3879:       /* } */
                   3880:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3881:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3882:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3883:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3884:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3885:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3886:       /*       } */
                   3887:       /*       /\* 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]); *\/ */
                   3888:       /* } */
                   3889:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3890:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3891:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3892:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3893:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3894:       /*         }else{ */
                   3895:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3896:       /*         } */
                   3897:       /*       }else{ */
                   3898:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3899:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3900:       /*         }else{ */
                   3901:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3902:       /*         } */
                   3903:       /*       } */
                   3904:       /* }                      */
                   3905:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3906:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3907: /** End of old code */
                   3908:       
1.218     brouard  3909:       /* Careful transposed matrix */
1.266     brouard  3910:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3911:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3912:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3913:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3914:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3915:       /* if((int)age == 70){ */
                   3916:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3917:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3918:       /*         printf("%d pmmij ",i); */
                   3919:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3920:       /*           printf("%f ",pmmij[i][j]); */
                   3921:       /*         } */
                   3922:       /*         printf(" oldm "); */
                   3923:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3924:       /*           printf("%f ",oldm[i][j]); */
                   3925:       /*         } */
                   3926:       /*         printf("\n"); */
                   3927:       /*       } */
                   3928:       /* } */
                   3929:       savm=oldm;
                   3930:       oldm=newm;
                   3931:     }
                   3932:     for(i=1; i<=nlstate+ndeath; i++)
                   3933:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3934:        po[i][j][h]=newm[i][j];
1.268     brouard  3935:        /* if(h==nhstepm) */
                   3936:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3937:       }
1.268     brouard  3938:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3939:   } /* end h */
1.268     brouard  3940:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3941:   return po;
                   3942: }
                   3943: 
                   3944: 
1.162     brouard  3945: #ifdef NLOPT
                   3946:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3947:   double fret;
                   3948:   double *xt;
                   3949:   int j;
                   3950:   myfunc_data *d2 = (myfunc_data *) pd;
                   3951: /* xt = (p1-1); */
                   3952:   xt=vector(1,n); 
                   3953:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3954: 
                   3955:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3956:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3957:   printf("Function = %.12lf ",fret);
                   3958:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3959:   printf("\n");
                   3960:  free_vector(xt,1,n);
                   3961:   return fret;
                   3962: }
                   3963: #endif
1.126     brouard  3964: 
                   3965: /*************** log-likelihood *************/
                   3966: double func( double *x)
                   3967: {
1.336     brouard  3968:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3969:   int ioffset=0;
1.339     brouard  3970:   int ipos=0,iposold=0,ncovv=0;
                   3971: 
1.340     brouard  3972:   double cotvarv, cotvarvold;
1.226     brouard  3973:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3974:   double **out;
                   3975:   double lli; /* Individual log likelihood */
                   3976:   int s1, s2;
1.228     brouard  3977:   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  3978: 
1.226     brouard  3979:   double bbh, survp;
                   3980:   double agexact;
1.336     brouard  3981:   double agebegin, ageend;
1.226     brouard  3982:   /*extern weight */
                   3983:   /* We are differentiating ll according to initial status */
                   3984:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3985:   /*for(i=1;i<imx;i++) 
                   3986:     printf(" %d\n",s[4][i]);
                   3987:   */
1.162     brouard  3988: 
1.226     brouard  3989:   ++countcallfunc;
1.162     brouard  3990: 
1.226     brouard  3991:   cov[1]=1.;
1.126     brouard  3992: 
1.226     brouard  3993:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3994:   ioffset=0;
1.226     brouard  3995:   if(mle==1){
                   3996:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3997:       /* Computes the values of the ncovmodel covariates of the model
                   3998:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3999:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4000:         to be observed in j being in i according to the model.
                   4001:       */
1.243     brouard  4002:       ioffset=2+nagesqr ;
1.233     brouard  4003:    /* Fixed */
1.345     brouard  4004:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4005:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4006:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4007:        /*  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  4008:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4009:        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  4010:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4011:       }
1.226     brouard  4012:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4013:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4014:         has been calculated etc */
                   4015:       /* For an individual i, wav[i] gives the number of effective waves */
                   4016:       /* We compute the contribution to Likelihood of each effective transition
                   4017:         mw[mi][i] is real wave of the mi th effectve wave */
                   4018:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4019:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4020:         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  4021:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4022:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4023:       */
1.336     brouard  4024:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4025:       /* Wave varying (but not age varying) */
1.339     brouard  4026:        /* 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*\/ */
                   4027:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4028:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4029:        /* } */
1.340     brouard  4030:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4031:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4032:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4033:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4034:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4035:          }else{ /* fixed covariate */
1.345     brouard  4036:            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  4037:          }
1.339     brouard  4038:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4039:            cotvarvold=cotvarv;
                   4040:          }else{ /* A second product */
                   4041:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4042:          }
                   4043:          iposold=ipos;
1.340     brouard  4044:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4045:        }
1.339     brouard  4046:        /* for products of time varying to be done */
1.234     brouard  4047:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4048:          for (j=1;j<=nlstate+ndeath;j++){
                   4049:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4050:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4051:          }
1.336     brouard  4052: 
                   4053:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4054:        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  4055:        for(d=0; d<dh[mi][i]; d++){
                   4056:          newm=savm;
                   4057:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4058:          cov[2]=agexact;
                   4059:          if(nagesqr==1)
                   4060:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349   ! brouard  4061:          /* for (kk=1; kk<=cptcovage;kk++) { */
        !          4062:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
        !          4063:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
        !          4064:          /*   else */
        !          4065:          /*     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) *\/  */
        !          4066:          /* } */
        !          4067:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          4068:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          4069:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4070:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          4071:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
        !          4072:            }else{ /* fixed covariate */
        !          4073:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
        !          4074:            }
        !          4075:            if(ipos!=iposold){ /* Not a product or first of a product */
        !          4076:              cotvarvold=cotvarv;
        !          4077:            }else{ /* A second product */
        !          4078:              cotvarv=cotvarv*cotvarvold;
        !          4079:            }
        !          4080:            iposold=ipos;
        !          4081:            cov[ioffset+ipos]=cotvarv*agexact;
        !          4082:            /* For products */
1.234     brouard  4083:          }
1.349   ! brouard  4084:          
1.234     brouard  4085:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4086:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4087:          savm=oldm;
                   4088:          oldm=newm;
                   4089:        } /* end mult */
                   4090:        
                   4091:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4092:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4093:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4094:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4095:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4096:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4097:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4098:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4099:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4100:                                 * -stepm/2 to stepm/2 .
                   4101:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4102:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4103:                                 */
1.234     brouard  4104:        s1=s[mw[mi][i]][i];
                   4105:        s2=s[mw[mi+1][i]][i];
                   4106:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4107:        /* bias bh is positive if real duration
                   4108:         * is higher than the multiple of stepm and negative otherwise.
                   4109:         */
                   4110:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4111:        if( s2 > nlstate){ 
                   4112:          /* i.e. if s2 is a death state and if the date of death is known 
                   4113:             then the contribution to the likelihood is the probability to 
                   4114:             die between last step unit time and current  step unit time, 
                   4115:             which is also equal to probability to die before dh 
                   4116:             minus probability to die before dh-stepm . 
                   4117:             In version up to 0.92 likelihood was computed
                   4118:             as if date of death was unknown. Death was treated as any other
                   4119:             health state: the date of the interview describes the actual state
                   4120:             and not the date of a change in health state. The former idea was
                   4121:             to consider that at each interview the state was recorded
                   4122:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4123:             introduced the exact date of death then we should have modified
                   4124:             the contribution of an exact death to the likelihood. This new
                   4125:             contribution is smaller and very dependent of the step unit
                   4126:             stepm. It is no more the probability to die between last interview
                   4127:             and month of death but the probability to survive from last
                   4128:             interview up to one month before death multiplied by the
                   4129:             probability to die within a month. Thanks to Chris
                   4130:             Jackson for correcting this bug.  Former versions increased
                   4131:             mortality artificially. The bad side is that we add another loop
                   4132:             which slows down the processing. The difference can be up to 10%
                   4133:             lower mortality.
                   4134:          */
                   4135:          /* If, at the beginning of the maximization mostly, the
                   4136:             cumulative probability or probability to be dead is
                   4137:             constant (ie = 1) over time d, the difference is equal to
                   4138:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4139:             s1 at precedent wave, to be dead a month before current
                   4140:             wave is equal to probability, being at state s1 at
                   4141:             precedent wave, to be dead at mont of the current
                   4142:             wave. Then the observed probability (that this person died)
                   4143:             is null according to current estimated parameter. In fact,
                   4144:             it should be very low but not zero otherwise the log go to
                   4145:             infinity.
                   4146:          */
1.183     brouard  4147: /* #ifdef INFINITYORIGINAL */
                   4148: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4149: /* #else */
                   4150: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4151: /*         lli=log(mytinydouble); */
                   4152: /*       else */
                   4153: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4154: /* #endif */
1.226     brouard  4155:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4156:          
1.226     brouard  4157:        } else if  ( s2==-1 ) { /* alive */
                   4158:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4159:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4160:          /*survp += out[s1][j]; */
                   4161:          lli= log(survp);
                   4162:        }
1.336     brouard  4163:        /* else if  (s2==-4) {  */
                   4164:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4165:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4166:        /*   lli= log(survp);  */
                   4167:        /* }  */
                   4168:        /* else if  (s2==-5) {  */
                   4169:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4170:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4171:        /*   lli= log(survp);  */
                   4172:        /* }  */
1.226     brouard  4173:        else{
                   4174:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4175:          /*  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 */
                   4176:        } 
                   4177:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4178:        /*if(lli ==000.0)*/
1.340     brouard  4179:        /* 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  4180:        ipmx +=1;
                   4181:        sw += weight[i];
                   4182:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4183:        /* if (lli < log(mytinydouble)){ */
                   4184:        /*   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); */
                   4185:        /*   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]); */
                   4186:        /* } */
                   4187:       } /* end of wave */
                   4188:     } /* end of individual */
                   4189:   }  else if(mle==2){
                   4190:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4191:       ioffset=2+nagesqr ;
                   4192:       for (k=1; k<=ncovf;k++)
                   4193:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4194:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4195:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4196:          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  4197:        }
1.226     brouard  4198:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4199:          for (j=1;j<=nlstate+ndeath;j++){
                   4200:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4201:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4202:          }
                   4203:        for(d=0; d<=dh[mi][i]; d++){
                   4204:          newm=savm;
                   4205:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4206:          cov[2]=agexact;
                   4207:          if(nagesqr==1)
                   4208:            cov[3]= agexact*agexact;
                   4209:          for (kk=1; kk<=cptcovage;kk++) {
                   4210:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4211:          }
                   4212:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4213:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4214:          savm=oldm;
                   4215:          oldm=newm;
                   4216:        } /* end mult */
                   4217:       
                   4218:        s1=s[mw[mi][i]][i];
                   4219:        s2=s[mw[mi+1][i]][i];
                   4220:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4221:        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 */
                   4222:        ipmx +=1;
                   4223:        sw += weight[i];
                   4224:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4225:       } /* end of wave */
                   4226:     } /* end of individual */
                   4227:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4228:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4229:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4230:       for(mi=1; mi<= wav[i]-1; mi++){
                   4231:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4232:          for (j=1;j<=nlstate+ndeath;j++){
                   4233:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4234:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4235:          }
                   4236:        for(d=0; d<dh[mi][i]; d++){
                   4237:          newm=savm;
                   4238:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4239:          cov[2]=agexact;
                   4240:          if(nagesqr==1)
                   4241:            cov[3]= agexact*agexact;
                   4242:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4243:            if(!FixedV[Tvar[Tage[kk]]])
                   4244:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4245:            else
1.341     brouard  4246:              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  4247:          }
                   4248:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4249:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4250:          savm=oldm;
                   4251:          oldm=newm;
                   4252:        } /* end mult */
                   4253:       
                   4254:        s1=s[mw[mi][i]][i];
                   4255:        s2=s[mw[mi+1][i]][i];
                   4256:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4257:        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 */
                   4258:        ipmx +=1;
                   4259:        sw += weight[i];
                   4260:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4261:       } /* end of wave */
                   4262:     } /* end of individual */
                   4263:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4264:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4265:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4266:       for(mi=1; mi<= wav[i]-1; mi++){
                   4267:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4268:          for (j=1;j<=nlstate+ndeath;j++){
                   4269:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4270:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4271:          }
                   4272:        for(d=0; d<dh[mi][i]; d++){
                   4273:          newm=savm;
                   4274:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4275:          cov[2]=agexact;
                   4276:          if(nagesqr==1)
                   4277:            cov[3]= agexact*agexact;
                   4278:          for (kk=1; kk<=cptcovage;kk++) {
                   4279:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4280:          }
1.126     brouard  4281:        
1.226     brouard  4282:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4283:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4284:          savm=oldm;
                   4285:          oldm=newm;
                   4286:        } /* end mult */
                   4287:       
                   4288:        s1=s[mw[mi][i]][i];
                   4289:        s2=s[mw[mi+1][i]][i];
                   4290:        if( s2 > nlstate){ 
                   4291:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4292:        } else if  ( s2==-1 ) { /* alive */
                   4293:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4294:            survp += out[s1][j];
                   4295:          lli= log(survp);
                   4296:        }else{
                   4297:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4298:        }
                   4299:        ipmx +=1;
                   4300:        sw += weight[i];
                   4301:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4302:        /* 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  4303:       } /* end of wave */
                   4304:     } /* end of individual */
                   4305:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4306:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4307:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4308:       for(mi=1; mi<= wav[i]-1; mi++){
                   4309:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4310:          for (j=1;j<=nlstate+ndeath;j++){
                   4311:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4312:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4313:          }
                   4314:        for(d=0; d<dh[mi][i]; d++){
                   4315:          newm=savm;
                   4316:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4317:          cov[2]=agexact;
                   4318:          if(nagesqr==1)
                   4319:            cov[3]= agexact*agexact;
                   4320:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4321:            if(!FixedV[Tvar[Tage[kk]]])
                   4322:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4323:            else
1.341     brouard  4324:              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  4325:          }
1.126     brouard  4326:        
1.226     brouard  4327:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4328:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4329:          savm=oldm;
                   4330:          oldm=newm;
                   4331:        } /* end mult */
                   4332:       
                   4333:        s1=s[mw[mi][i]][i];
                   4334:        s2=s[mw[mi+1][i]][i];
                   4335:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4336:        ipmx +=1;
                   4337:        sw += weight[i];
                   4338:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4339:        /*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]);*/
                   4340:       } /* end of wave */
                   4341:     } /* end of individual */
                   4342:   } /* End of if */
                   4343:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4344:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4345:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4346:   return -l;
1.126     brouard  4347: }
                   4348: 
                   4349: /*************** log-likelihood *************/
                   4350: double funcone( double *x)
                   4351: {
1.228     brouard  4352:   /* Same as func but slower because of a lot of printf and if */
1.349   ! brouard  4353:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4354:   int ioffset=0;
1.339     brouard  4355:   int ipos=0,iposold=0,ncovv=0;
                   4356: 
1.340     brouard  4357:   double cotvarv, cotvarvold;
1.131     brouard  4358:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4359:   double **out;
                   4360:   double lli; /* Individual log likelihood */
                   4361:   double llt;
                   4362:   int s1, s2;
1.228     brouard  4363:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4364: 
1.126     brouard  4365:   double bbh, survp;
1.187     brouard  4366:   double agexact;
1.214     brouard  4367:   double agebegin, ageend;
1.126     brouard  4368:   /*extern weight */
                   4369:   /* We are differentiating ll according to initial status */
                   4370:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4371:   /*for(i=1;i<imx;i++) 
                   4372:     printf(" %d\n",s[4][i]);
                   4373:   */
                   4374:   cov[1]=1.;
                   4375: 
                   4376:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4377:   ioffset=0;
                   4378:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4379:     /* Computes the values of the ncovmodel covariates of the model
                   4380:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4381:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4382:        to be observed in j being in i according to the model.
                   4383:     */
1.243     brouard  4384:     /* ioffset=2+nagesqr+cptcovage; */
                   4385:     ioffset=2+nagesqr;
1.232     brouard  4386:     /* Fixed */
1.224     brouard  4387:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4388:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349   ! brouard  4389:     for (kf=1; kf<=ncovf;kf++){ /*  V2  +  V3  +  V4  Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4390:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4391:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4392:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4393:       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  4394: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4395: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4396: /*    cov[2+6]=covar[2][i]; V2  */
                   4397: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4398: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4399: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4400: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4401: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4402: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4403:     }
1.336     brouard  4404:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4405:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4406:         has been calculated etc */
                   4407:       /* For an individual i, wav[i] gives the number of effective waves */
                   4408:       /* We compute the contribution to Likelihood of each effective transition
                   4409:         mw[mi][i] is real wave of the mi th effectve wave */
                   4410:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4411:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4412:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4413:       */
                   4414:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4415:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4416:     /*   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?)*\/ */
                   4417:     /* } */
1.231     brouard  4418:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4419:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4420:     /* } */
1.225     brouard  4421:     
1.233     brouard  4422: 
                   4423:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4424:       /* 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 */
                   4425:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4426:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4427:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4428:       /* } */
                   4429:       
                   4430:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4431:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4432:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4433:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4434:       /* We need the position of the time varying or product in the model */
                   4435:       /* 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 */            
                   4436:       /* TvarVV gives the variable name */
1.340     brouard  4437:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4438:       *      k=         1   2     3     4         5        6        7       8        9
                   4439:       *  varying            1     2                                 3       4        5
                   4440:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4441:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4442:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4443:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4444:       */
1.345     brouard  4445:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349   ! brouard  4446:        * 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[(v6*V2)6]=9
1.345     brouard  4447:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349   ! brouard  4448:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
        !          4449:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
        !          4450:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
        !          4451:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
        !          4452:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
        !          4453:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
        !          4454:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
        !          4455:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
        !          4456:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
        !          4457:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
        !          4458:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
        !          4459:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
        !          4460:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
        !          4461:        *                  12       13      14      15       16
        !          4462:        *                    17        18         19        20         21
        !          4463:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
        !          4464:        *                   2       3        4       6        7
        !          4465:        *                     9         11          12        13         14            
        !          4466:        * cptcovage=5+5 total of covariates with age 
        !          4467:        * Tage[cptcovage] age*V2=12      13      14      15       16
        !          4468:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
        !          4469:        *3 Tage[cptcovage] age*V3*V2=6  
        !          4470:        *3                age*V2=12         13      14      15       16
        !          4471:        *3                age*V6*V3=18      19    20   21
        !          4472:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
        !          4473:        *     Tvar[17]age*V6*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
        !          4474:        * 2   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
        !          4475:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
        !          4476:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
        !          4477:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
        !          4478:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
        !          4479:        * 3   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
        !          4480:        * Tvar=                {2, 3, 4, 6, 7,
        !          4481:        *                       9, 10, 11, 12, 13, 14,
        !          4482:        *              Tvar[12]=2, 3, 4, 6, 7,
        !          4483:        *              Tvar[17]=9, 11, 12, 13, 14}
        !          4484:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
        !          4485:        *                  2, 2, 2, 2, 2, 2,
        !          4486:        * 3                3, 2, 2, 2, 2, 2,
        !          4487:        *                  1, 1, 1, 1, 1, 
        !          4488:        *                  3, 3, 3, 3, 3}
        !          4489:        * 3                 2, 3, 3, 3, 3}
        !          4490:        * p Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6} Id of the prod at position k in the model
        !          4491:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
        !          4492:        * 3 Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6}
        !          4493:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
        !          4494:        * cptcovprod=11 (6+5)
        !          4495:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
        !          4496:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
        !          4497:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
        !          4498:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
        !          4499:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
        !          4500:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
        !          4501:        * cptcovdageprod=5  for gnuplot printing
        !          4502:        * cptcovprodvage=6 
        !          4503:        * ncova=15           1        2       3       4       5
        !          4504:        *                      6 7        8 9      10 11        12 13     14 15
        !          4505:        * TvarA              2        3       4       6       7
        !          4506:        *                      6 2        6 7       7 3          6 4       7 4
        !          4507:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4508:        * ncovf            1     2      3
1.349   ! brouard  4509:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
        !          4510:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
        !          4511:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
        !          4512:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
        !          4513:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
        !          4514:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
        !          4515:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
        !          4516:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
        !          4517:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
        !          4518:        * 3 cptcovprodvage=6
        !          4519:        * 3 ncovta=15    +age*V3*V2+age*V2+agev3+ageV4 +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
        !          4520:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
        !          4521:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
        !          4522:        * TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
        !          4523:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
        !          4524:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
        !          4525:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
        !          4526:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
        !          4527:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
        !          4528:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
        !          4529:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
        !          4530:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4531:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349   ! brouard  4532:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
        !          4533:        *                   2, 3, 4, 6, 7,
        !          4534:        *                     6, 8, 9, 10, 11}
1.345     brouard  4535:        * TvarFind[itv]                        0      0       0
                   4536:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4537:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4538:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4539:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349   ! brouard  4540:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4541:        */
                   4542: 
1.349   ! brouard  4543:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /*  V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4 Time varying  covariates (single and extended product but no age) including individual from products, product is computed dynamically */
        !          4544:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, or fixed covariate of a varying product after exploding product Vn*Vm into Vn and then Vm  */
1.340     brouard  4545:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4546:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4547:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4548:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4549:        }else{ /* fixed covariate */
1.345     brouard  4550:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
1.349   ! brouard  4551:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.340     brouard  4552:        }
1.339     brouard  4553:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4554:          cotvarvold=cotvarv;
                   4555:        }else{ /* A second product */
                   4556:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4557:        }
                   4558:        iposold=ipos;
1.340     brouard  4559:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4560:        /* For products */
                   4561:       }
                   4562:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4563:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4564:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4565:       /*       /\*           1  2   3      4      5                         *\/ */
                   4566:       /*       /\*itv           1                                           *\/ */
                   4567:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4568:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4569:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4570:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4571:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4572:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4573:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4574:       /*       /\* 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]); *\/ */
                   4575:       /* } */
1.232     brouard  4576:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4577:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4578:       /*       /\* 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]); *\/ */
                   4579:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4580:       /* } */
1.126     brouard  4581:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4582:        for (j=1;j<=nlstate+ndeath;j++){
                   4583:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4584:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4585:        }
1.214     brouard  4586:       
                   4587:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4588:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4589:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4590:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4591:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4592:          and mw[mi+1][i]. dh depends on stepm.*/
                   4593:        newm=savm;
1.247     brouard  4594:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4595:        cov[2]=agexact;
                   4596:        if(nagesqr==1)
                   4597:          cov[3]= agexact*agexact;
1.349   ! brouard  4598:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          4599:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          4600:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4601:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
        !          4602:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          4603:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          4604:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
        !          4605:          }else{ /* fixed covariate */
        !          4606:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
        !          4607:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          4608:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
        !          4609:          }
        !          4610:          if(ipos!=iposold){ /* Not a product or first of a product */
        !          4611:            cotvarvold=cotvarv;
        !          4612:          }else{ /* A second product */
        !          4613:            /* printf("DEBUG * \n"); */
        !          4614:            cotvarv=cotvarv*cotvarvold;
        !          4615:          }
        !          4616:          iposold=ipos;
        !          4617:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
        !          4618:          cov[ioffset+ipos]=cotvarv*agexact;
        !          4619:          /* For products */
1.242     brouard  4620:        }
1.349   ! brouard  4621: 
1.242     brouard  4622:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4623:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4624:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4625:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4626:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4627:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4628:        savm=oldm;
                   4629:        oldm=newm;
1.126     brouard  4630:       } /* end mult */
1.336     brouard  4631:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4632:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4633:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4634:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4635:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4636:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4637:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4638:         * probability in order to take into account the bias as a fraction of the way
                   4639:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4640:                                 * -stepm/2 to stepm/2 .
                   4641:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4642:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4643:                                 */
1.126     brouard  4644:       s1=s[mw[mi][i]][i];
                   4645:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4646:       /* if(s2==-1){ */
1.268     brouard  4647:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4648:       /*       /\* exit(1); *\/ */
                   4649:       /* } */
1.126     brouard  4650:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4651:       /* bias is positive if real duration
                   4652:        * is higher than the multiple of stepm and negative otherwise.
                   4653:        */
                   4654:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4655:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4656:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4657:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4658:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4659:        lli= log(survp);
1.126     brouard  4660:       }else if (mle==1){
1.242     brouard  4661:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4662:       } else if(mle==2){
1.242     brouard  4663:        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  4664:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4665:        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  4666:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4667:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4668:       } else{  /* mle=0 back to 1 */
1.242     brouard  4669:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4670:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4671:       } /* End of if */
                   4672:       ipmx +=1;
                   4673:       sw += weight[i];
                   4674:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4675:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4676:       /* 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  4677:       if(globpr){
1.246     brouard  4678:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4679:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4680:                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  4681:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4682:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4683:        /* %11.6f %11.6f %11.6f ", \ */
                   4684:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4685:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4686:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4687:          llt +=ll[k]*gipmx/gsw;
                   4688:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4689:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4690:        }
1.343     brouard  4691:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4692:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4693:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4694:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4695:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4696:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4697:        }
                   4698:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4699:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4700:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4701:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4702:            /* printf(" %g",cov[ioffset+ipos]); */
                   4703:          }else{
                   4704:            fprintf(ficresilk,"*");
                   4705:            /* printf("*"); */
1.342     brouard  4706:          }
1.343     brouard  4707:          iposold=ipos;
                   4708:        }
1.349   ! brouard  4709:        /* for (kk=1; kk<=cptcovage;kk++) { */
        !          4710:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
        !          4711:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
        !          4712:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
        !          4713:        /*   }else{ */
        !          4714:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
        !          4715:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
        !          4716:        /*   } */
        !          4717:        /* } */
        !          4718:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          4719:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          4720:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4721:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
        !          4722:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          4723:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          4724:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
        !          4725:          }else{ /* fixed covariate */
        !          4726:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
        !          4727:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          4728:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
        !          4729:          }
        !          4730:          if(ipos!=iposold){ /* Not a product or first of a product */
        !          4731:            cotvarvold=cotvarv;
        !          4732:          }else{ /* A second product */
        !          4733:            /* printf("DEBUG * \n"); */
        !          4734:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4735:          }
1.349   ! brouard  4736:          cotvarv=cotvarv*agexact;
        !          4737:          fprintf(ficresilk," %g*age",cotvarv);
        !          4738:          iposold=ipos;
        !          4739:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
        !          4740:          cov[ioffset+ipos]=cotvarv;
        !          4741:          /* For products */
1.343     brouard  4742:        }
                   4743:        /* printf("\n"); */
1.342     brouard  4744:        /* } /\*  End debugILK *\/ */
                   4745:        fprintf(ficresilk,"\n");
                   4746:       } /* End if globpr */
1.335     brouard  4747:     } /* end of wave */
                   4748:   } /* end of individual */
                   4749:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4750: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4751:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4752:   if(globpr==0){ /* First time we count the contributions and weights */
                   4753:     gipmx=ipmx;
                   4754:     gsw=sw;
                   4755:   }
1.343     brouard  4756:   return -l;
1.126     brouard  4757: }
                   4758: 
                   4759: 
                   4760: /*************** function likelione ***********/
1.292     brouard  4761: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4762: {
                   4763:   /* This routine should help understanding what is done with 
                   4764:      the selection of individuals/waves and
                   4765:      to check the exact contribution to the likelihood.
                   4766:      Plotting could be done.
1.342     brouard  4767:   */
                   4768:   void pstamp(FILE *ficres);
1.343     brouard  4769:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4770: 
                   4771:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4772:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4773:     strcat(fileresilk,fileresu);
1.126     brouard  4774:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4775:       printf("Problem with resultfile: %s\n", fileresilk);
                   4776:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4777:     }
1.342     brouard  4778:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4779:     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");
                   4780:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4781:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4782:     for(k=1; k<=nlstate; k++) 
                   4783:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4784:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4785: 
                   4786:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4787:       for(kf=1;kf <= ncovf; kf++){
                   4788:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4789:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4790:       }
                   4791:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4792:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4793:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4794:          /* printf(" %d",ipos); */
                   4795:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4796:        }else{
                   4797:          /* printf("*"); */
                   4798:          fprintf(ficresilk,"*");
1.343     brouard  4799:        }
1.342     brouard  4800:        iposold=ipos;
                   4801:       }
                   4802:       for (kk=1; kk<=cptcovage;kk++) {
                   4803:        if(!FixedV[Tvar[Tage[kk]]]){
                   4804:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4805:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4806:        }else{
                   4807:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4808:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4809:        }
                   4810:       }
                   4811:     /* } /\* End if debugILK *\/ */
                   4812:     /* printf("\n"); */
                   4813:     fprintf(ficresilk,"\n");
                   4814:   } /* End glogpri */
1.126     brouard  4815: 
1.292     brouard  4816:   *fretone=(*func)(p);
1.126     brouard  4817:   if(*globpri !=0){
                   4818:     fclose(ficresilk);
1.205     brouard  4819:     if (mle ==0)
                   4820:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4821:     else if(mle >=1)
                   4822:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4823:     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  4824:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4825:       
1.207     brouard  4826:     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  4827: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4828:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4829: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4830:     
                   4831:     for (k=1; k<= nlstate ; k++) {
                   4832:       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 \
                   4833: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4834:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   4835:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
                   4836:        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> \
                   4837: <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]]);
                   4838:       }
                   4839:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4840:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4841:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4842:        /* 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]); */
                   4843:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4844:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4845:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4846:          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)  */
                   4847:            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> \
                   4848: <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);
                   4849:          } /* End only for dummies time varying (single?) */
                   4850:        }else{ /* Useless product */
                   4851:          /* printf("*"); */
                   4852:          /* fprintf(ficresilk,"*"); */ 
                   4853:        }
                   4854:        iposold=ipos;
                   4855:       } /* For each time varying covariate */
                   4856:     } /* End loop on states */
                   4857: 
                   4858: /*     if(debugILK){ */
                   4859: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4860: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4861: /*     for (k=1; k<= nlstate ; k++) { */
                   4862: /*       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> \ */
                   4863: /* <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]]); */
                   4864: /*     } */
                   4865: /*       } */
                   4866: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4867: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4868: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4869: /*     /\* 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]); *\/ */
                   4870: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4871: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4872: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4873: /*       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)  *\/ */
                   4874: /*         for (k=1; k<= nlstate ; k++) { */
                   4875: /*           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> \ */
                   4876: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4877: /*         } /\* End state *\/ */
                   4878: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4879: /*     }else{ /\* Useless product *\/ */
                   4880: /*       /\* printf("*"); *\/ */
                   4881: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4882: /*     } */
                   4883: /*     iposold=ipos; */
                   4884: /*       } /\* For each time varying covariate *\/ */
                   4885: /*     }/\* End debugILK *\/ */
1.207     brouard  4886:     fflush(fichtm);
1.343     brouard  4887:   }/* End globpri */
1.126     brouard  4888:   return;
                   4889: }
                   4890: 
                   4891: 
                   4892: /*********** Maximum Likelihood Estimation ***************/
                   4893: 
                   4894: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4895: {
1.319     brouard  4896:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4897:   double **xi;
                   4898:   double fret;
                   4899:   double fretone; /* Only one call to likelihood */
                   4900:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4901: 
                   4902: #ifdef NLOPT
                   4903:   int creturn;
                   4904:   nlopt_opt opt;
                   4905:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4906:   double *lb;
                   4907:   double minf; /* the minimum objective value, upon return */
                   4908:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4909:   myfunc_data dinst, *d = &dinst;
                   4910: #endif
                   4911: 
                   4912: 
1.126     brouard  4913:   xi=matrix(1,npar,1,npar);
                   4914:   for (i=1;i<=npar;i++)
                   4915:     for (j=1;j<=npar;j++)
                   4916:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4917:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4918:   strcpy(filerespow,"POW_"); 
1.126     brouard  4919:   strcat(filerespow,fileres);
                   4920:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4921:     printf("Problem with resultfile: %s\n", filerespow);
                   4922:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4923:   }
                   4924:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4925:   for (i=1;i<=nlstate;i++)
                   4926:     for(j=1;j<=nlstate+ndeath;j++)
                   4927:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4928:   fprintf(ficrespow,"\n");
1.162     brouard  4929: #ifdef POWELL
1.319     brouard  4930: #ifdef LINMINORIGINAL
                   4931: #else /* LINMINORIGINAL */
                   4932:   
                   4933:   flatdir=ivector(1,npar); 
                   4934:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4935: #endif /*LINMINORIGINAL */
                   4936: 
                   4937: #ifdef FLATSUP
                   4938:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4939:   /* reorganizing p by suppressing flat directions */
                   4940:   for(i=1, jk=1; i <=nlstate; i++){
                   4941:     for(k=1; k <=(nlstate+ndeath); k++){
                   4942:       if (k != i) {
                   4943:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4944:         if(flatdir[jk]==1){
                   4945:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4946:         }
                   4947:         for(j=1; j <=ncovmodel; j++){
                   4948:           printf("%12.7f ",p[jk]);
                   4949:           jk++; 
                   4950:         }
                   4951:         printf("\n");
                   4952:       }
                   4953:     }
                   4954:   }
                   4955: /* skipping */
                   4956:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4957:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4958:     for(k=1; k <=(nlstate+ndeath); k++){
                   4959:       if (k != i) {
                   4960:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4961:         if(flatdir[jk]==1){
                   4962:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4963:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4964:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4965:             /*q[jjk]=p[jk];*/
                   4966:           }
                   4967:         }else{
                   4968:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4969:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4970:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4971:             /*q[jjk]=p[jk];*/
                   4972:           }
                   4973:         }
                   4974:         printf("\n");
                   4975:       }
                   4976:       fflush(stdout);
                   4977:     }
                   4978:   }
                   4979:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4980: #else  /* FLATSUP */
1.126     brouard  4981:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4982: #endif  /* FLATSUP */
                   4983: 
                   4984: #ifdef LINMINORIGINAL
                   4985: #else
                   4986:       free_ivector(flatdir,1,npar); 
                   4987: #endif  /* LINMINORIGINAL*/
                   4988: #endif /* POWELL */
1.126     brouard  4989: 
1.162     brouard  4990: #ifdef NLOPT
                   4991: #ifdef NEWUOA
                   4992:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4993: #else
                   4994:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4995: #endif
                   4996:   lb=vector(0,npar-1);
                   4997:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4998:   nlopt_set_lower_bounds(opt, lb);
                   4999:   nlopt_set_initial_step1(opt, 0.1);
                   5000:   
                   5001:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5002:   d->function = func;
                   5003:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5004:   nlopt_set_min_objective(opt, myfunc, d);
                   5005:   nlopt_set_xtol_rel(opt, ftol);
                   5006:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5007:     printf("nlopt failed! %d\n",creturn); 
                   5008:   }
                   5009:   else {
                   5010:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5011:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5012:     iter=1; /* not equal */
                   5013:   }
                   5014:   nlopt_destroy(opt);
                   5015: #endif
1.319     brouard  5016: #ifdef FLATSUP
                   5017:   /* npared = npar -flatd/ncovmodel; */
                   5018:   /* xired= matrix(1,npared,1,npared); */
                   5019:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5020:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5021:   /* free_matrix(xire,1,npared,1,npared); */
                   5022: #else  /* FLATSUP */
                   5023: #endif /* FLATSUP */
1.126     brouard  5024:   free_matrix(xi,1,npar,1,npar);
                   5025:   fclose(ficrespow);
1.203     brouard  5026:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5027:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5028:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5029: 
                   5030: }
                   5031: 
                   5032: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5033: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5034: {
                   5035:   double  **a,**y,*x,pd;
1.203     brouard  5036:   /* double **hess; */
1.164     brouard  5037:   int i, j;
1.126     brouard  5038:   int *indx;
                   5039: 
                   5040:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5041:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5042:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5043:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5044:   double gompertz(double p[]);
1.203     brouard  5045:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5046: 
                   5047:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5048:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5049:   for (i=1;i<=npar;i++){
1.203     brouard  5050:     printf("%d-",i);fflush(stdout);
                   5051:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5052:    
                   5053:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5054:     
                   5055:     /*  printf(" %f ",p[i]);
                   5056:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5057:   }
                   5058:   
                   5059:   for (i=1;i<=npar;i++) {
                   5060:     for (j=1;j<=npar;j++)  {
                   5061:       if (j>i) { 
1.203     brouard  5062:        printf(".%d-%d",i,j);fflush(stdout);
                   5063:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5064:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5065:        
                   5066:        hess[j][i]=hess[i][j];    
                   5067:        /*printf(" %lf ",hess[i][j]);*/
                   5068:       }
                   5069:     }
                   5070:   }
                   5071:   printf("\n");
                   5072:   fprintf(ficlog,"\n");
                   5073: 
                   5074:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5075:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5076:   
                   5077:   a=matrix(1,npar,1,npar);
                   5078:   y=matrix(1,npar,1,npar);
                   5079:   x=vector(1,npar);
                   5080:   indx=ivector(1,npar);
                   5081:   for (i=1;i<=npar;i++)
                   5082:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5083:   ludcmp(a,npar,indx,&pd);
                   5084: 
                   5085:   for (j=1;j<=npar;j++) {
                   5086:     for (i=1;i<=npar;i++) x[i]=0;
                   5087:     x[j]=1;
                   5088:     lubksb(a,npar,indx,x);
                   5089:     for (i=1;i<=npar;i++){ 
                   5090:       matcov[i][j]=x[i];
                   5091:     }
                   5092:   }
                   5093: 
                   5094:   printf("\n#Hessian matrix#\n");
                   5095:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5096:   for (i=1;i<=npar;i++) { 
                   5097:     for (j=1;j<=npar;j++) { 
1.203     brouard  5098:       printf("%.6e ",hess[i][j]);
                   5099:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5100:     }
                   5101:     printf("\n");
                   5102:     fprintf(ficlog,"\n");
                   5103:   }
                   5104: 
1.203     brouard  5105:   /* printf("\n#Covariance matrix#\n"); */
                   5106:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5107:   /* for (i=1;i<=npar;i++) {  */
                   5108:   /*   for (j=1;j<=npar;j++) {  */
                   5109:   /*     printf("%.6e ",matcov[i][j]); */
                   5110:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5111:   /*   } */
                   5112:   /*   printf("\n"); */
                   5113:   /*   fprintf(ficlog,"\n"); */
                   5114:   /* } */
                   5115: 
1.126     brouard  5116:   /* Recompute Inverse */
1.203     brouard  5117:   /* for (i=1;i<=npar;i++) */
                   5118:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5119:   /* ludcmp(a,npar,indx,&pd); */
                   5120: 
                   5121:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5122: 
                   5123:   /* for (j=1;j<=npar;j++) { */
                   5124:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5125:   /*   x[j]=1; */
                   5126:   /*   lubksb(a,npar,indx,x); */
                   5127:   /*   for (i=1;i<=npar;i++){  */
                   5128:   /*     y[i][j]=x[i]; */
                   5129:   /*     printf("%.3e ",y[i][j]); */
                   5130:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5131:   /*   } */
                   5132:   /*   printf("\n"); */
                   5133:   /*   fprintf(ficlog,"\n"); */
                   5134:   /* } */
                   5135: 
                   5136:   /* Verifying the inverse matrix */
                   5137: #ifdef DEBUGHESS
                   5138:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5139: 
1.203     brouard  5140:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5141:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5142: 
                   5143:   for (j=1;j<=npar;j++) {
                   5144:     for (i=1;i<=npar;i++){ 
1.203     brouard  5145:       printf("%.2f ",y[i][j]);
                   5146:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5147:     }
                   5148:     printf("\n");
                   5149:     fprintf(ficlog,"\n");
                   5150:   }
1.203     brouard  5151: #endif
1.126     brouard  5152: 
                   5153:   free_matrix(a,1,npar,1,npar);
                   5154:   free_matrix(y,1,npar,1,npar);
                   5155:   free_vector(x,1,npar);
                   5156:   free_ivector(indx,1,npar);
1.203     brouard  5157:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5158: 
                   5159: 
                   5160: }
                   5161: 
                   5162: /*************** hessian matrix ****************/
                   5163: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5164: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5165:   int i;
                   5166:   int l=1, lmax=20;
1.203     brouard  5167:   double k1,k2, res, fx;
1.132     brouard  5168:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5169:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5170:   int k=0,kmax=10;
                   5171:   double l1;
                   5172: 
                   5173:   fx=func(x);
                   5174:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5175:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5176:     l1=pow(10,l);
                   5177:     delts=delt;
                   5178:     for(k=1 ; k <kmax; k=k+1){
                   5179:       delt = delta*(l1*k);
                   5180:       p2[theta]=x[theta] +delt;
1.145     brouard  5181:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5182:       p2[theta]=x[theta]-delt;
                   5183:       k2=func(p2)-fx;
                   5184:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5185:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5186:       
1.203     brouard  5187: #ifdef DEBUGHESSII
1.126     brouard  5188:       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);
                   5189:       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);
                   5190: #endif
                   5191:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5192:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5193:        k=kmax;
                   5194:       }
                   5195:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5196:        k=kmax; l=lmax*10;
1.126     brouard  5197:       }
                   5198:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5199:        delts=delt;
                   5200:       }
1.203     brouard  5201:     } /* End loop k */
1.126     brouard  5202:   }
                   5203:   delti[theta]=delts;
                   5204:   return res; 
                   5205:   
                   5206: }
                   5207: 
1.203     brouard  5208: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5209: {
                   5210:   int i;
1.164     brouard  5211:   int l=1, lmax=20;
1.126     brouard  5212:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5213:   double p2[MAXPARM+1];
1.203     brouard  5214:   int k, kmax=1;
                   5215:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5216: 
                   5217:   int firstime=0;
1.203     brouard  5218:   
1.126     brouard  5219:   fx=func(x);
1.203     brouard  5220:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5221:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5222:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5223:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5224:     k1=func(p2)-fx;
                   5225:   
1.203     brouard  5226:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5227:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5228:     k2=func(p2)-fx;
                   5229:   
1.203     brouard  5230:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5231:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5232:     k3=func(p2)-fx;
                   5233:   
1.203     brouard  5234:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5235:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5236:     k4=func(p2)-fx;
1.203     brouard  5237:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5238:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5239:       firstime=1;
1.203     brouard  5240:       kmax=kmax+10;
1.208     brouard  5241:     }
                   5242:     if(kmax >=10 || firstime ==1){
1.246     brouard  5243:       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);
                   5244:       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  5245:       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);
                   5246:       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);
                   5247:     }
                   5248: #ifdef DEBUGHESSIJ
                   5249:     v1=hess[thetai][thetai];
                   5250:     v2=hess[thetaj][thetaj];
                   5251:     cv12=res;
                   5252:     /* Computing eigen value of Hessian matrix */
                   5253:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5254:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5255:     if ((lc2 <0) || (lc1 <0) ){
                   5256:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5257:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5258:       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);
                   5259:       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);
                   5260:     }
1.126     brouard  5261: #endif
                   5262:   }
                   5263:   return res;
                   5264: }
                   5265: 
1.203     brouard  5266:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5267: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5268: /* { */
                   5269: /*   int i; */
                   5270: /*   int l=1, lmax=20; */
                   5271: /*   double k1,k2,k3,k4,res,fx; */
                   5272: /*   double p2[MAXPARM+1]; */
                   5273: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5274: /*   int k=0,kmax=10; */
                   5275: /*   double l1; */
                   5276:   
                   5277: /*   fx=func(x); */
                   5278: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5279: /*     l1=pow(10,l); */
                   5280: /*     delts=delt; */
                   5281: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5282: /*       delt = delti*(l1*k); */
                   5283: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5284: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5285: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5286: /*       k1=func(p2)-fx; */
                   5287:       
                   5288: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5289: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5290: /*       k2=func(p2)-fx; */
                   5291:       
                   5292: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5293: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5294: /*       k3=func(p2)-fx; */
                   5295:       
                   5296: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5297: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5298: /*       k4=func(p2)-fx; */
                   5299: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5300: /* #ifdef DEBUGHESSIJ */
                   5301: /*       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); */
                   5302: /*       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); */
                   5303: /* #endif */
                   5304: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5305: /*     k=kmax; */
                   5306: /*       } */
                   5307: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5308: /*     k=kmax; l=lmax*10; */
                   5309: /*       } */
                   5310: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5311: /*     delts=delt; */
                   5312: /*       } */
                   5313: /*     } /\* End loop k *\/ */
                   5314: /*   } */
                   5315: /*   delti[theta]=delts; */
                   5316: /*   return res;  */
                   5317: /* } */
                   5318: 
                   5319: 
1.126     brouard  5320: /************** Inverse of matrix **************/
                   5321: void ludcmp(double **a, int n, int *indx, double *d) 
                   5322: { 
                   5323:   int i,imax,j,k; 
                   5324:   double big,dum,sum,temp; 
                   5325:   double *vv; 
                   5326:  
                   5327:   vv=vector(1,n); 
                   5328:   *d=1.0; 
                   5329:   for (i=1;i<=n;i++) { 
                   5330:     big=0.0; 
                   5331:     for (j=1;j<=n;j++) 
                   5332:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5333:     if (big == 0.0){
                   5334:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5335:       for (j=1;j<=n;j++) {
                   5336:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5337:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5338:       }
                   5339:       fflush(ficlog);
                   5340:       fclose(ficlog);
                   5341:       nrerror("Singular matrix in routine ludcmp"); 
                   5342:     }
1.126     brouard  5343:     vv[i]=1.0/big; 
                   5344:   } 
                   5345:   for (j=1;j<=n;j++) { 
                   5346:     for (i=1;i<j;i++) { 
                   5347:       sum=a[i][j]; 
                   5348:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5349:       a[i][j]=sum; 
                   5350:     } 
                   5351:     big=0.0; 
                   5352:     for (i=j;i<=n;i++) { 
                   5353:       sum=a[i][j]; 
                   5354:       for (k=1;k<j;k++) 
                   5355:        sum -= a[i][k]*a[k][j]; 
                   5356:       a[i][j]=sum; 
                   5357:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5358:        big=dum; 
                   5359:        imax=i; 
                   5360:       } 
                   5361:     } 
                   5362:     if (j != imax) { 
                   5363:       for (k=1;k<=n;k++) { 
                   5364:        dum=a[imax][k]; 
                   5365:        a[imax][k]=a[j][k]; 
                   5366:        a[j][k]=dum; 
                   5367:       } 
                   5368:       *d = -(*d); 
                   5369:       vv[imax]=vv[j]; 
                   5370:     } 
                   5371:     indx[j]=imax; 
                   5372:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5373:     if (j != n) { 
                   5374:       dum=1.0/(a[j][j]); 
                   5375:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5376:     } 
                   5377:   } 
                   5378:   free_vector(vv,1,n);  /* Doesn't work */
                   5379: ;
                   5380: } 
                   5381: 
                   5382: void lubksb(double **a, int n, int *indx, double b[]) 
                   5383: { 
                   5384:   int i,ii=0,ip,j; 
                   5385:   double sum; 
                   5386:  
                   5387:   for (i=1;i<=n;i++) { 
                   5388:     ip=indx[i]; 
                   5389:     sum=b[ip]; 
                   5390:     b[ip]=b[i]; 
                   5391:     if (ii) 
                   5392:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5393:     else if (sum) ii=i; 
                   5394:     b[i]=sum; 
                   5395:   } 
                   5396:   for (i=n;i>=1;i--) { 
                   5397:     sum=b[i]; 
                   5398:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5399:     b[i]=sum/a[i][i]; 
                   5400:   } 
                   5401: } 
                   5402: 
                   5403: void pstamp(FILE *fichier)
                   5404: {
1.196     brouard  5405:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5406: }
                   5407: 
1.297     brouard  5408: void date2dmy(double date,double *day, double *month, double *year){
                   5409:   double yp=0., yp1=0., yp2=0.;
                   5410:   
                   5411:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5412:                        fractional in yp1 */
                   5413:   *year=yp;
                   5414:   yp2=modf((yp1*12),&yp);
                   5415:   *month=yp;
                   5416:   yp1=modf((yp2*30.5),&yp);
                   5417:   *day=yp;
                   5418:   if(*day==0) *day=1;
                   5419:   if(*month==0) *month=1;
                   5420: }
                   5421: 
1.253     brouard  5422: 
                   5423: 
1.126     brouard  5424: /************ Frequencies ********************/
1.251     brouard  5425: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5426:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5427:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5428: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5429:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5430:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5431:   int iind=0, iage=0;
                   5432:   int mi; /* Effective wave */
                   5433:   int first;
                   5434:   double ***freq; /* Frequencies */
1.268     brouard  5435:   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 */
                   5436:   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  5437:   double *meanq, *stdq, *idq;
1.226     brouard  5438:   double **meanqt;
                   5439:   double *pp, **prop, *posprop, *pospropt;
                   5440:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5441:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5442:   double agebegin, ageend;
                   5443:     
                   5444:   pp=vector(1,nlstate);
1.251     brouard  5445:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5446:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5447:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5448:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5449:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5450:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5451:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5452:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5453:   strcpy(fileresp,"P_");
                   5454:   strcat(fileresp,fileresu);
                   5455:   /*strcat(fileresphtm,fileresu);*/
                   5456:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5457:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5458:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5459:     exit(0);
                   5460:   }
1.240     brouard  5461:   
1.226     brouard  5462:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5463:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5464:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5465:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5466:     fflush(ficlog);
                   5467:     exit(70); 
                   5468:   }
                   5469:   else{
                   5470:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5471: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5472: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5473:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5474:   }
1.319     brouard  5475:   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  5476:   
1.226     brouard  5477:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5478:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5479:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5480:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5481:     fflush(ficlog);
                   5482:     exit(70); 
1.240     brouard  5483:   } else{
1.226     brouard  5484:     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  5485: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5486: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5487:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5488:   }
1.319     brouard  5489:   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  5490:   
1.253     brouard  5491:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5492:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5493:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5494:   j1=0;
1.126     brouard  5495:   
1.227     brouard  5496:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5497:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5498:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5499:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5500:   
                   5501:   
1.226     brouard  5502:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5503:      reference=low_education V1=0,V2=0
                   5504:      med_educ                V1=1 V2=0, 
                   5505:      high_educ               V1=0 V2=1
1.330     brouard  5506:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5507:   */
1.249     brouard  5508:   dateintsum=0;
                   5509:   k2cpt=0;
                   5510: 
1.253     brouard  5511:   if(cptcoveff == 0 )
1.265     brouard  5512:     nl=1;  /* Constant and age model only */
1.253     brouard  5513:   else
                   5514:     nl=2;
1.265     brouard  5515: 
                   5516:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5517:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5518:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5519:    *     freq[s1][s2][iage] =0.
                   5520:    *     Loop on iind
                   5521:    *       ++freq[s1][s2][iage] weighted
                   5522:    *     end iind
                   5523:    *     if covariate and j!0
                   5524:    *       headers Variable on one line
                   5525:    *     endif cov j!=0
                   5526:    *     header of frequency table by age
                   5527:    *     Loop on age
                   5528:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5529:    *       pos+=freq[s1][s2][iage] weighted
                   5530:    *       Loop on s1 initial state
                   5531:    *         fprintf(ficresp
                   5532:    *       end s1
                   5533:    *     end age
                   5534:    *     if j!=0 computes starting values
                   5535:    *     end compute starting values
                   5536:    *   end j1
                   5537:    * end nl 
                   5538:    */
1.253     brouard  5539:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5540:     if(nj==1)
                   5541:       j=0;  /* First pass for the constant */
1.265     brouard  5542:     else{
1.335     brouard  5543:       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  5544:     }
1.251     brouard  5545:     first=1;
1.332     brouard  5546:     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  5547:       posproptt=0.;
1.330     brouard  5548:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5549:        scanf("%d", i);*/
                   5550:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5551:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5552:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5553:            freq[i][s2][m]=0;
1.251     brouard  5554:       
                   5555:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5556:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5557:          prop[i][m]=0;
                   5558:        posprop[i]=0;
                   5559:        pospropt[i]=0;
                   5560:       }
1.283     brouard  5561:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5562:         idq[z1]=0.;
                   5563:         meanq[z1]=0.;
                   5564:         stdq[z1]=0.;
1.283     brouard  5565:       }
                   5566:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5567:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5568:       /*         meanqt[m][z1]=0.; */
                   5569:       /*       } */
                   5570:       /* }       */
1.251     brouard  5571:       /* dateintsum=0; */
                   5572:       /* k2cpt=0; */
                   5573:       
1.265     brouard  5574:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5575:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5576:        bool=1;
                   5577:        if(j !=0){
                   5578:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5579:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5580:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5581:                /* if(Tvaraff[z1] ==-20){ */
                   5582:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5583:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5584:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5585:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5586:                /* 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); */
                   5587:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5588:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5589:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5590:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5591:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5592:                  /* 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", */
                   5593:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5594:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5595:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5596:                } /* Onlyf fixed */
                   5597:              } /* end z1 */
1.335     brouard  5598:            } /* cptcoveff > 0 */
1.251     brouard  5599:          } /* end any */
                   5600:        }/* end j==0 */
1.265     brouard  5601:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5602:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5603:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5604:            m=mw[mi][iind];
                   5605:            if(j!=0){
                   5606:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5607:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5608:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5609:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5610:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5611:                    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  5612:                                                                                      value is -1, we don't select. It differs from the 
                   5613:                                                                                      constant and age model which counts them. */
                   5614:                      bool=0; /* not selected */
                   5615:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5616:                    /* i1=Tvaraff[z1]; */
                   5617:                    /* i2=TnsdVar[i1]; */
                   5618:                    /* i3=nbcode[i1][i2]; */
                   5619:                    /* i4=covar[i1][iind]; */
                   5620:                    /* if(i4 != i3){ */
                   5621:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5622:                      bool=0;
                   5623:                    }
                   5624:                  }
                   5625:                }
                   5626:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5627:            } /* end j==0 */
                   5628:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5629:            if(bool==1){ /*Selected */
1.251     brouard  5630:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5631:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5632:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5633:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5634:              if(m >=firstpass && m <=lastpass){
                   5635:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5636:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5637:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5638:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5639:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5640:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5641:                if (m<lastpass) {
                   5642:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5643:                  /*   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]); */
                   5644:                  if(s[m][iind]==-1)
                   5645:                    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.));
                   5646:                  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  5647:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5648:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5649:                      idq[z1]=idq[z1]+weight[iind];
                   5650:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5651:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5652:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5653:                    }
1.284     brouard  5654:                  }
1.251     brouard  5655:                  /* if((int)agev[m][iind] == 55) */
                   5656:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5657:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5658:                  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  5659:                }
1.251     brouard  5660:              } /* end if between passes */  
                   5661:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5662:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5663:                k2cpt++;
                   5664:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5665:              }
1.251     brouard  5666:            }else{
                   5667:              bool=1;
                   5668:            }/* end bool 2 */
                   5669:          } /* end m */
1.284     brouard  5670:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5671:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5672:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5673:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5674:          /* } */
1.251     brouard  5675:        } /* end bool */
                   5676:       } /* end iind = 1 to imx */
1.319     brouard  5677:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5678:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5679:       
                   5680:       
                   5681:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5682:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5683:         pstamp(ficresp);
1.335     brouard  5684:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5685:         pstamp(ficresp);
1.251     brouard  5686:        printf( "\n#********** Variable "); 
                   5687:        fprintf(ficresp, "\n#********** Variable "); 
                   5688:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5689:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5690:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5691:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5692:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5693:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5694:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5695:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5696:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5697:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5698:          }else{
1.330     brouard  5699:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5700:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5701:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5702:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5703:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5704:          }
                   5705:        }
                   5706:        printf( "**********\n#");
                   5707:        fprintf(ficresp, "**********\n#");
                   5708:        fprintf(ficresphtm, "**********</h3>\n");
                   5709:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5710:        fprintf(ficlog, "**********\n");
                   5711:       }
1.284     brouard  5712:       /*
                   5713:        Printing means of quantitative variables if any
                   5714:       */
                   5715:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5716:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5717:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5718:        if(weightopt==1){
                   5719:          printf(" Weighted mean and standard deviation of");
                   5720:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5721:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5722:        }
1.311     brouard  5723:        /* mu = \frac{w x}{\sum w}
                   5724:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5725:        */
                   5726:        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]));
                   5727:        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]));
                   5728:        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  5729:       }
                   5730:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5731:       /*       for(m=1;m<=lastpass;m++){ */
                   5732:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5733:       /*   } */
                   5734:       /* } */
1.283     brouard  5735: 
1.251     brouard  5736:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5737:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5738:         fprintf(ficresp, " Age");
1.335     brouard  5739:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5740:          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]]);
                   5741:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5742:        }
1.251     brouard  5743:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5744:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5745:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5746:       }
1.335     brouard  5747:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5748:       fprintf(ficresphtm, "\n");
                   5749:       
                   5750:       /* Header of frequency table by age */
                   5751:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5752:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5753:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5754:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5755:          if(s2!=0 && m!=0)
                   5756:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5757:        }
1.226     brouard  5758:       }
1.251     brouard  5759:       fprintf(ficresphtmfr, "\n");
                   5760:     
                   5761:       /* For each age */
                   5762:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5763:        fprintf(ficresphtm,"<tr>");
                   5764:        if(iage==iagemax+1){
                   5765:          fprintf(ficlog,"1");
                   5766:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5767:        }else if(iage==iagemax+2){
                   5768:          fprintf(ficlog,"0");
                   5769:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5770:        }else if(iage==iagemax+3){
                   5771:          fprintf(ficlog,"Total");
                   5772:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5773:        }else{
1.240     brouard  5774:          if(first==1){
1.251     brouard  5775:            first=0;
                   5776:            printf("See log file for details...\n");
                   5777:          }
                   5778:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5779:          fprintf(ficlog,"Age %d", iage);
                   5780:        }
1.265     brouard  5781:        for(s1=1; s1 <=nlstate ; s1++){
                   5782:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5783:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5784:        }
1.265     brouard  5785:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5786:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5787:            pos += freq[s1][m][iage];
                   5788:          if(pp[s1]>=1.e-10){
1.251     brouard  5789:            if(first==1){
1.265     brouard  5790:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5791:            }
1.265     brouard  5792:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5793:          }else{
                   5794:            if(first==1)
1.265     brouard  5795:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5796:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5797:          }
                   5798:        }
                   5799:       
1.265     brouard  5800:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5801:          /* posprop[s1]=0; */
                   5802:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5803:            pp[s1] += freq[s1][m][iage];
                   5804:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5805:       
                   5806:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5807:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5808:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5809:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5810:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5811:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5812:        }
                   5813:        
                   5814:        /* Writing ficresp */
1.335     brouard  5815:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5816:           if( iage <= iagemax){
                   5817:            fprintf(ficresp," %d",iage);
                   5818:           }
                   5819:         }else if( nj==2){
                   5820:           if( iage <= iagemax){
                   5821:            fprintf(ficresp," %d",iage);
1.335     brouard  5822:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5823:           }
1.240     brouard  5824:        }
1.265     brouard  5825:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5826:          if(pos>=1.e-5){
1.251     brouard  5827:            if(first==1)
1.265     brouard  5828:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5829:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5830:          }else{
                   5831:            if(first==1)
1.265     brouard  5832:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5833:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5834:          }
                   5835:          if( iage <= iagemax){
                   5836:            if(pos>=1.e-5){
1.335     brouard  5837:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5838:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5839:               }else if( nj==2){
                   5840:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5841:               }
                   5842:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5843:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5844:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5845:            } else{
1.335     brouard  5846:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5847:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5848:            }
1.240     brouard  5849:          }
1.265     brouard  5850:          pospropt[s1] +=posprop[s1];
                   5851:        } /* end loop s1 */
1.251     brouard  5852:        /* pospropt=0.; */
1.265     brouard  5853:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5854:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5855:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5856:              if(first==1){
1.265     brouard  5857:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5858:              }
1.265     brouard  5859:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5860:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5861:            }
1.265     brouard  5862:            if(s1!=0 && m!=0)
                   5863:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5864:          }
1.265     brouard  5865:        } /* end loop s1 */
1.251     brouard  5866:        posproptt=0.; 
1.265     brouard  5867:        for(s1=1; s1 <=nlstate; s1++){
                   5868:          posproptt += pospropt[s1];
1.251     brouard  5869:        }
                   5870:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5871:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5872:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5873:          if(iage <= iagemax)
                   5874:            fprintf(ficresp,"\n");
1.240     brouard  5875:        }
1.251     brouard  5876:        if(first==1)
                   5877:          printf("Others in log...\n");
                   5878:        fprintf(ficlog,"\n");
                   5879:       } /* end loop age iage */
1.265     brouard  5880:       
1.251     brouard  5881:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5882:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5883:        if(posproptt < 1.e-5){
1.265     brouard  5884:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5885:        }else{
1.265     brouard  5886:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5887:        }
1.226     brouard  5888:       }
1.251     brouard  5889:       fprintf(ficresphtm,"</tr>\n");
                   5890:       fprintf(ficresphtm,"</table>\n");
                   5891:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5892:       if(posproptt < 1.e-5){
1.251     brouard  5893:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5894:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5895:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5896:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5897:        invalidvarcomb[j1]=1;
1.226     brouard  5898:       }else{
1.338     brouard  5899:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5900:        invalidvarcomb[j1]=0;
1.226     brouard  5901:       }
1.251     brouard  5902:       fprintf(ficresphtmfr,"</table>\n");
                   5903:       fprintf(ficlog,"\n");
                   5904:       if(j!=0){
                   5905:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5906:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5907:          for(k=1; k <=(nlstate+ndeath); k++){
                   5908:            if (k != i) {
1.265     brouard  5909:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5910:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5911:                  if(j1==1){ /* All dummy covariates to zero */
                   5912:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5913:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5914:                    printf("%d%d ",i,k);
                   5915:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5916:                    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]));
                   5917:                    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]));
                   5918:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5919:                  }
1.253     brouard  5920:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5921:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5922:                    x[iage]= (double)iage;
                   5923:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5924:                    /* 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  5925:                  }
1.268     brouard  5926:                  /* Some are not finite, but linreg will ignore these ages */
                   5927:                  no=0;
1.253     brouard  5928:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5929:                  pstart[s1]=b;
                   5930:                  pstart[s1-1]=a;
1.252     brouard  5931:                }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 */ 
                   5932:                  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]);
                   5933:                  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  5934:                  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  5935:                  printf("%d%d ",i,k);
                   5936:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5937:                  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  5938:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5939:                  ;
                   5940:                }
                   5941:                /* printf("%12.7f )", param[i][jj][k]); */
                   5942:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5943:                s1++; 
1.251     brouard  5944:              } /* end jj */
                   5945:            } /* end k!= i */
                   5946:          } /* end k */
1.265     brouard  5947:        } /* end i, s1 */
1.251     brouard  5948:       } /* end j !=0 */
                   5949:     } /* end selected combination of covariate j1 */
                   5950:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5951:       printf("#Freqsummary: Starting values for the constants:\n");
                   5952:       fprintf(ficlog,"\n");
1.265     brouard  5953:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5954:        for(k=1; k <=(nlstate+ndeath); k++){
                   5955:          if (k != i) {
                   5956:            printf("%d%d ",i,k);
                   5957:            fprintf(ficlog,"%d%d ",i,k);
                   5958:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5959:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5960:              if(jj==1){ /* Age has to be done */
1.265     brouard  5961:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5962:                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]));
                   5963:                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  5964:              }
                   5965:              /* printf("%12.7f )", param[i][jj][k]); */
                   5966:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5967:              s1++; 
1.250     brouard  5968:            }
1.251     brouard  5969:            printf("\n");
                   5970:            fprintf(ficlog,"\n");
1.250     brouard  5971:          }
                   5972:        }
1.284     brouard  5973:       } /* end of state i */
1.251     brouard  5974:       printf("#Freqsummary\n");
                   5975:       fprintf(ficlog,"\n");
1.265     brouard  5976:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5977:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5978:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5979:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5980:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5981:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5982:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5983:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5984:          /* } */
                   5985:        }
1.265     brouard  5986:       } /* end loop s1 */
1.251     brouard  5987:       
                   5988:       printf("\n");
                   5989:       fprintf(ficlog,"\n");
                   5990:     } /* end j=0 */
1.249     brouard  5991:   } /* end j */
1.252     brouard  5992: 
1.253     brouard  5993:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5994:     for(i=1, jk=1; i <=nlstate; i++){
                   5995:       for(j=1; j <=nlstate+ndeath; j++){
                   5996:        if(j!=i){
                   5997:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5998:          printf("%1d%1d",i,j);
                   5999:          fprintf(ficparo,"%1d%1d",i,j);
                   6000:          for(k=1; k<=ncovmodel;k++){
                   6001:            /*    printf(" %lf",param[i][j][k]); */
                   6002:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6003:            p[jk]=pstart[jk];
                   6004:            printf(" %f ",pstart[jk]);
                   6005:            fprintf(ficparo," %f ",pstart[jk]);
                   6006:            jk++;
                   6007:          }
                   6008:          printf("\n");
                   6009:          fprintf(ficparo,"\n");
                   6010:        }
                   6011:       }
                   6012:     }
                   6013:   } /* end mle=-2 */
1.226     brouard  6014:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6015:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6016:   
1.226     brouard  6017:   fclose(ficresp);
                   6018:   fclose(ficresphtm);
                   6019:   fclose(ficresphtmfr);
1.283     brouard  6020:   free_vector(idq,1,nqfveff);
1.226     brouard  6021:   free_vector(meanq,1,nqfveff);
1.284     brouard  6022:   free_vector(stdq,1,nqfveff);
1.226     brouard  6023:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6024:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6025:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6026:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6027:   free_vector(pospropt,1,nlstate);
                   6028:   free_vector(posprop,1,nlstate);
1.251     brouard  6029:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6030:   free_vector(pp,1,nlstate);
                   6031:   /* End of freqsummary */
                   6032: }
1.126     brouard  6033: 
1.268     brouard  6034: /* Simple linear regression */
                   6035: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6036: 
                   6037:   /* y=a+bx regression */
                   6038:   double   sumx = 0.0;                        /* sum of x                      */
                   6039:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6040:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6041:   double   sumy = 0.0;                        /* sum of y                      */
                   6042:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6043:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6044:   double yhat;
                   6045:   
                   6046:   double denom=0;
                   6047:   int i;
                   6048:   int ne=*no;
                   6049:   
                   6050:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6051:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6052:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6053:       continue;
                   6054:     }
                   6055:     ne=ne+1;
                   6056:     sumx  += x[i];       
                   6057:     sumx2 += x[i]*x[i];  
                   6058:     sumxy += x[i] * y[i];
                   6059:     sumy  += y[i];      
                   6060:     sumy2 += y[i]*y[i]; 
                   6061:     denom = (ne * sumx2 - sumx*sumx);
                   6062:     /* 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); */
                   6063:   } 
                   6064:   
                   6065:   denom = (ne * sumx2 - sumx*sumx);
                   6066:   if (denom == 0) {
                   6067:     // vertical, slope m is infinity
                   6068:     *b = INFINITY;
                   6069:     *a = 0;
                   6070:     if (r) *r = 0;
                   6071:     return 1;
                   6072:   }
                   6073:   
                   6074:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6075:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6076:   if (r!=NULL) {
                   6077:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6078:       sqrt((sumx2 - sumx*sumx/ne) *
                   6079:           (sumy2 - sumy*sumy/ne));
                   6080:   }
                   6081:   *no=ne;
                   6082:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6083:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6084:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6085:       continue;
                   6086:     }
                   6087:     ne=ne+1;
                   6088:     yhat = y[i] - *a -*b* x[i];
                   6089:     sume2  += yhat * yhat ;       
                   6090:     
                   6091:     denom = (ne * sumx2 - sumx*sumx);
                   6092:     /* 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); */
                   6093:   } 
                   6094:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6095:   *sa= *sb * sqrt(sumx2/ne);
                   6096:   
                   6097:   return 0; 
                   6098: }
                   6099: 
1.126     brouard  6100: /************ Prevalence ********************/
1.227     brouard  6101: 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)
                   6102: {  
                   6103:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6104:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6105:      We still use firstpass and lastpass as another selection.
                   6106:   */
1.126     brouard  6107:  
1.227     brouard  6108:   int i, m, jk, j1, bool, z1,j, iv;
                   6109:   int mi; /* Effective wave */
                   6110:   int iage;
                   6111:   double agebegin, ageend;
                   6112: 
                   6113:   double **prop;
                   6114:   double posprop; 
                   6115:   double  y2; /* in fractional years */
                   6116:   int iagemin, iagemax;
                   6117:   int first; /** to stop verbosity which is redirected to log file */
                   6118: 
                   6119:   iagemin= (int) agemin;
                   6120:   iagemax= (int) agemax;
                   6121:   /*pp=vector(1,nlstate);*/
1.251     brouard  6122:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6123:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6124:   j1=0;
1.222     brouard  6125:   
1.227     brouard  6126:   /*j=cptcoveff;*/
                   6127:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6128:   
1.288     brouard  6129:   first=0;
1.335     brouard  6130:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6131:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6132:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6133:        prop[i][iage]=0.0;
                   6134:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6135:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6136:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6137:     
                   6138:     for (i=1; i<=imx; i++) { /* Each individual */
                   6139:       bool=1;
                   6140:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6141:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6142:        m=mw[mi][i];
                   6143:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6144:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6145:        for (z1=1; z1<=cptcoveff; z1++){
                   6146:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6147:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6148:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6149:              bool=0;
                   6150:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6151:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6152:              bool=0;
                   6153:            }
                   6154:        }
                   6155:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6156:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6157:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6158:          if(m >=firstpass && m <=lastpass){
                   6159:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6160:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6161:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6162:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6163:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6164:                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); 
                   6165:                exit(1);
                   6166:              }
                   6167:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6168:                /*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]]);*/
                   6169:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6170:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6171:              } /* end valid statuses */ 
                   6172:            } /* end selection of dates */
                   6173:          } /* end selection of waves */
                   6174:        } /* end bool */
                   6175:       } /* end wave */
                   6176:     } /* end individual */
                   6177:     for(i=iagemin; i <= iagemax+3; i++){  
                   6178:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6179:        posprop += prop[jk][i]; 
                   6180:       } 
                   6181:       
                   6182:       for(jk=1; jk <=nlstate ; jk++){      
                   6183:        if( i <=  iagemax){ 
                   6184:          if(posprop>=1.e-5){ 
                   6185:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6186:          } else{
1.288     brouard  6187:            if(!first){
                   6188:              first=1;
1.266     brouard  6189:              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]);
                   6190:            }else{
1.288     brouard  6191:              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  6192:            }
                   6193:          }
                   6194:        } 
                   6195:       }/* end jk */ 
                   6196:     }/* end i */ 
1.222     brouard  6197:      /*} *//* end i1 */
1.227     brouard  6198:   } /* end j1 */
1.222     brouard  6199:   
1.227     brouard  6200:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6201:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6202:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6203: }  /* End of prevalence */
1.126     brouard  6204: 
                   6205: /************* Waves Concatenation ***************/
                   6206: 
                   6207: 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)
                   6208: {
1.298     brouard  6209:   /* 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  6210:      Death is a valid wave (if date is known).
                   6211:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6212:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6213:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6214:   */
1.126     brouard  6215: 
1.224     brouard  6216:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6217:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6218:      double sum=0., jmean=0.;*/
1.224     brouard  6219:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6220:   int j, k=0,jk, ju, jl;
                   6221:   double sum=0.;
                   6222:   first=0;
1.214     brouard  6223:   firstwo=0;
1.217     brouard  6224:   firsthree=0;
1.218     brouard  6225:   firstfour=0;
1.164     brouard  6226:   jmin=100000;
1.126     brouard  6227:   jmax=-1;
                   6228:   jmean=0.;
1.224     brouard  6229: 
                   6230: /* Treating live states */
1.214     brouard  6231:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6232:     mi=0;  /* First valid wave */
1.227     brouard  6233:     mli=0; /* Last valid wave */
1.309     brouard  6234:     m=firstpass;  /* Loop on waves */
                   6235:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6236:       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 */
                   6237:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6238:       }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  6239:        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  6240:        mli=m;
1.224     brouard  6241:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6242:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6243:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6244:       }
1.309     brouard  6245:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6246: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6247:        break;
1.224     brouard  6248: #else
1.317     brouard  6249:        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  6250:          if(firsthree == 0){
1.302     brouard  6251:            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  6252:            firsthree=1;
1.317     brouard  6253:          }else if(firsthree >=1 && firsthree < 10){
                   6254:            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);
                   6255:            firsthree++;
                   6256:          }else if(firsthree == 10){
                   6257:            printf("Information, too many Information flags: no more reported to log either\n");
                   6258:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6259:            firsthree++;
                   6260:          }else{
                   6261:            firsthree++;
1.227     brouard  6262:          }
1.309     brouard  6263:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6264:          mli=m;
                   6265:        }
                   6266:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6267:          nbwarn++;
1.309     brouard  6268:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6269:            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);
                   6270:            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);
                   6271:          }
                   6272:          break;
                   6273:        }
                   6274:        break;
1.224     brouard  6275: #endif
1.227     brouard  6276:       }/* End m >= lastpass */
1.126     brouard  6277:     }/* end while */
1.224     brouard  6278: 
1.227     brouard  6279:     /* 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  6280:     /* After last pass */
1.224     brouard  6281: /* Treating death states */
1.214     brouard  6282:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6283:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6284:       /* } */
1.126     brouard  6285:       mi++;    /* Death is another wave */
                   6286:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6287:       /* Only death is a correct wave */
1.126     brouard  6288:       mw[mi][i]=m;
1.257     brouard  6289:     } /* else not in a death state */
1.224     brouard  6290: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6291:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6292:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6293:        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  6294:          nbwarn++;
                   6295:          if(firstfiv==0){
1.309     brouard  6296:            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  6297:            firstfiv=1;
                   6298:          }else{
1.309     brouard  6299:            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  6300:          }
1.309     brouard  6301:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6302:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6303:          nberr++;
                   6304:          if(firstwo==0){
1.309     brouard  6305:            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  6306:            firstwo=1;
                   6307:          }
1.309     brouard  6308:          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  6309:        }
1.257     brouard  6310:       }else{ /* if date of interview is unknown */
1.227     brouard  6311:        /* death is known but not confirmed by death status at any wave */
                   6312:        if(firstfour==0){
1.309     brouard  6313:          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  6314:          firstfour=1;
                   6315:        }
1.309     brouard  6316:        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  6317:       }
1.224     brouard  6318:     } /* end if date of death is known */
                   6319: #endif
1.309     brouard  6320:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6321:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6322:     if(mi==0){
                   6323:       nbwarn++;
                   6324:       if(first==0){
1.227     brouard  6325:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6326:        first=1;
1.126     brouard  6327:       }
                   6328:       if(first==1){
1.227     brouard  6329:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6330:       }
                   6331:     } /* end mi==0 */
                   6332:   } /* End individuals */
1.214     brouard  6333:   /* wav and mw are no more changed */
1.223     brouard  6334:        
1.317     brouard  6335:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6336:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6337: 
                   6338: 
1.126     brouard  6339:   for(i=1; i<=imx; i++){
                   6340:     for(mi=1; mi<wav[i];mi++){
                   6341:       if (stepm <=0)
1.227     brouard  6342:        dh[mi][i]=1;
1.126     brouard  6343:       else{
1.260     brouard  6344:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6345:          if (agedc[i] < 2*AGESUP) {
                   6346:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6347:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6348:            else if(j<0){
                   6349:              nberr++;
                   6350:              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]);
                   6351:              j=1; /* Temporary Dangerous patch */
                   6352:              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);
                   6353:              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]);
                   6354:              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);
                   6355:            }
                   6356:            k=k+1;
                   6357:            if (j >= jmax){
                   6358:              jmax=j;
                   6359:              ijmax=i;
                   6360:            }
                   6361:            if (j <= jmin){
                   6362:              jmin=j;
                   6363:              ijmin=i;
                   6364:            }
                   6365:            sum=sum+j;
                   6366:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6367:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6368:          }
                   6369:        }
                   6370:        else{
                   6371:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6372: /*       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  6373:                                        
1.227     brouard  6374:          k=k+1;
                   6375:          if (j >= jmax) {
                   6376:            jmax=j;
                   6377:            ijmax=i;
                   6378:          }
                   6379:          else if (j <= jmin){
                   6380:            jmin=j;
                   6381:            ijmin=i;
                   6382:          }
                   6383:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6384:          /*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]);*/
                   6385:          if(j<0){
                   6386:            nberr++;
                   6387:            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]);
                   6388:            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]);
                   6389:          }
                   6390:          sum=sum+j;
                   6391:        }
                   6392:        jk= j/stepm;
                   6393:        jl= j -jk*stepm;
                   6394:        ju= j -(jk+1)*stepm;
                   6395:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6396:          if(jl==0){
                   6397:            dh[mi][i]=jk;
                   6398:            bh[mi][i]=0;
                   6399:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6400:                  * to avoid the price of an extra matrix product in likelihood */
                   6401:            dh[mi][i]=jk+1;
                   6402:            bh[mi][i]=ju;
                   6403:          }
                   6404:        }else{
                   6405:          if(jl <= -ju){
                   6406:            dh[mi][i]=jk;
                   6407:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6408:                                 * is higher than the multiple of stepm and negative otherwise.
                   6409:                                 */
                   6410:          }
                   6411:          else{
                   6412:            dh[mi][i]=jk+1;
                   6413:            bh[mi][i]=ju;
                   6414:          }
                   6415:          if(dh[mi][i]==0){
                   6416:            dh[mi][i]=1; /* At least one step */
                   6417:            bh[mi][i]=ju; /* At least one step */
                   6418:            /*  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);*/
                   6419:          }
                   6420:        } /* end if mle */
1.126     brouard  6421:       }
                   6422:     } /* end wave */
                   6423:   }
                   6424:   jmean=sum/k;
                   6425:   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  6426:   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  6427: }
1.126     brouard  6428: 
                   6429: /*********** Tricode ****************************/
1.220     brouard  6430:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6431:  {
                   6432:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6433:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6434:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6435:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6436:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6437:     */
1.130     brouard  6438: 
1.242     brouard  6439:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6440:    int modmaxcovj=0; /* Modality max of covariates j */
                   6441:    int cptcode=0; /* Modality max of covariates j */
                   6442:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6443: 
                   6444: 
1.242     brouard  6445:    /* cptcoveff=0;  */
                   6446:    /* *cptcov=0; */
1.126     brouard  6447:  
1.242     brouard  6448:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6449:    for (k=1; k <= maxncov; k++)
                   6450:      for(j=1; j<=2; j++)
                   6451:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6452: 
1.242     brouard  6453:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6454:    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  6455:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6456:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349   ! brouard  6457:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6458:        switch(Fixed[k]) {
                   6459:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6460:         modmaxcovj=0;
                   6461:         modmincovj=0;
1.242     brouard  6462:         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  6463:           /* 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  6464:           ij=(int)(covar[Tvar[k]][i]);
                   6465:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6466:            * If product of Vn*Vm, still boolean *:
                   6467:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6468:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6469:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6470:              modality of the nth covariate of individual i. */
                   6471:           if (ij > modmaxcovj)
                   6472:             modmaxcovj=ij; 
                   6473:           else if (ij < modmincovj) 
                   6474:             modmincovj=ij; 
1.287     brouard  6475:           if (ij <0 || ij >1 ){
1.311     brouard  6476:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6477:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6478:             fflush(ficlog);
                   6479:             exit(1);
1.287     brouard  6480:           }
                   6481:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6482:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6483:             exit(1);
                   6484:           }else
                   6485:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6486:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6487:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6488:           /* getting the maximum value of the modality of the covariate
                   6489:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6490:              female ies 1, then modmaxcovj=1.
                   6491:           */
                   6492:         } /* end for loop on individuals i */
                   6493:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6494:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6495:         cptcode=modmaxcovj;
                   6496:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6497:         /*for (i=0; i<=cptcode; i++) {*/
                   6498:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6499:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6500:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6501:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6502:             if( j != -1){
                   6503:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6504:                                  covariate for which somebody answered excluding 
                   6505:                                  undefined. Usually 2: 0 and 1. */
                   6506:             }
                   6507:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6508:                                     covariate for which somebody answered including 
                   6509:                                     undefined. Usually 3: -1, 0 and 1. */
                   6510:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6511:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6512:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6513:                        
1.242     brouard  6514:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6515:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6516:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6517:         /* modmincovj=3; modmaxcovj = 7; */
                   6518:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6519:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6520:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6521:         /* nbcode[Tvar[j]][ij]=k; */
                   6522:         /* nbcode[Tvar[j]][1]=0; */
                   6523:         /* nbcode[Tvar[j]][2]=1; */
                   6524:         /* nbcode[Tvar[j]][3]=2; */
                   6525:         /* To be continued (not working yet). */
                   6526:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6527: 
                   6528:         /* 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*/
                   6529:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6530:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6531:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6532:         /*, could be restored in the future */
                   6533:         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  6534:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6535:             break;
                   6536:           }
                   6537:           ij++;
1.287     brouard  6538:           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  6539:           cptcode = ij; /* New max modality for covar j */
                   6540:         } /* end of loop on modality i=-1 to 1 or more */
                   6541:         break;
                   6542:        case 1: /* Testing on varying covariate, could be simple and
                   6543:                * should look at waves or product of fixed *
                   6544:                * varying. No time to test -1, assuming 0 and 1 only */
                   6545:         ij=0;
                   6546:         for(i=0; i<=1;i++){
                   6547:           nbcode[Tvar[k]][++ij]=i;
                   6548:         }
                   6549:         break;
                   6550:        default:
                   6551:         break;
                   6552:        } /* end switch */
                   6553:      } /* end dummy test */
1.349   ! brouard  6554:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6555:        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  6556:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6557:           printf("Error k=%d \n",k);
                   6558:           exit(1);
                   6559:         }
1.311     brouard  6560:         if(isnan(covar[Tvar[k]][i])){
                   6561:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6562:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6563:           fflush(ficlog);
                   6564:           exit(1);
                   6565:          }
                   6566:        }
1.335     brouard  6567:      } /* end Quanti */
1.287     brouard  6568:    } /* 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  6569:   
                   6570:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6571:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6572:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6573:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6574:      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 */ 
                   6575:      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 */
                   6576:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6577:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6578:   
                   6579:    ij=0;
                   6580:    /* 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  6581:    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 */
                   6582:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6583:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6584:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6585:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6586:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6587:        /* 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  6588:        /* If product not in single variable we don't print results */
                   6589:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6590:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6591:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6592:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6593:        /* ij            1    2                                            3  */  
                   6594:        /* Tvaraff[ij]=  4    3                                            1  */
                   6595:        /* Tmodelind[ij]=2    3                                            9  */
                   6596:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6597:        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*/
                   6598:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6599:        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 */
                   6600:        if(Fixed[k]!=0)
                   6601:         anyvaryingduminmodel=1;
                   6602:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6603:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6604:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6605:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6606:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6607:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6608:      } 
                   6609:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6610:    /* ij--; */
                   6611:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6612:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6613:                * because they can be excluded from the model and real
                   6614:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6615:    for(j=ij+1; j<= cptcovt; j++){
                   6616:      Tvaraff[j]=0;
                   6617:      Tmodelind[j]=0;
                   6618:    }
                   6619:    for(j=ntveff+1; j<= cptcovt; j++){
                   6620:      TmodelInvind[j]=0;
                   6621:    }
                   6622:    /* To be sorted */
                   6623:    ;
                   6624:  }
1.126     brouard  6625: 
1.145     brouard  6626: 
1.126     brouard  6627: /*********** Health Expectancies ****************/
                   6628: 
1.235     brouard  6629:  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  6630: 
                   6631: {
                   6632:   /* Health expectancies, no variances */
1.329     brouard  6633:   /* cij is the combination in the list of combination of dummy covariates */
                   6634:   /* strstart is a string of time at start of computing */
1.164     brouard  6635:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6636:   int nhstepma, nstepma; /* Decreasing with age */
                   6637:   double age, agelim, hf;
                   6638:   double ***p3mat;
                   6639:   double eip;
                   6640: 
1.238     brouard  6641:   /* pstamp(ficreseij); */
1.126     brouard  6642:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6643:   fprintf(ficreseij,"# Age");
                   6644:   for(i=1; i<=nlstate;i++){
                   6645:     for(j=1; j<=nlstate;j++){
                   6646:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6647:     }
                   6648:     fprintf(ficreseij," e%1d. ",i);
                   6649:   }
                   6650:   fprintf(ficreseij,"\n");
                   6651: 
                   6652:   
                   6653:   if(estepm < stepm){
                   6654:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6655:   }
                   6656:   else  hstepm=estepm;   
                   6657:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6658:    * This is mainly to measure the difference between two models: for example
                   6659:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6660:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6661:    * progression in between and thus overestimating or underestimating according
                   6662:    * to the curvature of the survival function. If, for the same date, we 
                   6663:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6664:    * to compare the new estimate of Life expectancy with the same linear 
                   6665:    * hypothesis. A more precise result, taking into account a more precise
                   6666:    * curvature will be obtained if estepm is as small as stepm. */
                   6667: 
                   6668:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6669:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6670:      nhstepm is the number of hstepm from age to agelim 
                   6671:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6672:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6673:      and note for a fixed period like estepm months */
                   6674:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6675:      survival function given by stepm (the optimization length). Unfortunately it
                   6676:      means that if the survival funtion is printed only each two years of age and if
                   6677:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6678:      results. So we changed our mind and took the option of the best precision.
                   6679:   */
                   6680:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6681: 
                   6682:   agelim=AGESUP;
                   6683:   /* If stepm=6 months */
                   6684:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6685:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6686:     
                   6687: /* nhstepm age range expressed in number of stepm */
                   6688:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6689:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6690:   /* if (stepm >= YEARM) hstepm=1;*/
                   6691:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6692:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6693: 
                   6694:   for (age=bage; age<=fage; age ++){ 
                   6695:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6696:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6697:     /* if (stepm >= YEARM) hstepm=1;*/
                   6698:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6699: 
                   6700:     /* If stepm=6 months */
                   6701:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6702:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6703:     /* 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  6704:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6705:     
                   6706:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6707:     
                   6708:     printf("%d|",(int)age);fflush(stdout);
                   6709:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6710:     
                   6711:     /* Computing expectancies */
                   6712:     for(i=1; i<=nlstate;i++)
                   6713:       for(j=1; j<=nlstate;j++)
                   6714:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6715:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6716:          
                   6717:          /* 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]);*/
                   6718: 
                   6719:        }
                   6720: 
                   6721:     fprintf(ficreseij,"%3.0f",age );
                   6722:     for(i=1; i<=nlstate;i++){
                   6723:       eip=0;
                   6724:       for(j=1; j<=nlstate;j++){
                   6725:        eip +=eij[i][j][(int)age];
                   6726:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6727:       }
                   6728:       fprintf(ficreseij,"%9.4f", eip );
                   6729:     }
                   6730:     fprintf(ficreseij,"\n");
                   6731:     
                   6732:   }
                   6733:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6734:   printf("\n");
                   6735:   fprintf(ficlog,"\n");
                   6736:   
                   6737: }
                   6738: 
1.235     brouard  6739:  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  6740: 
                   6741: {
                   6742:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6743:      to initial status i, ei. .
1.126     brouard  6744:   */
1.336     brouard  6745:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6746:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6747:   int nhstepma, nstepma; /* Decreasing with age */
                   6748:   double age, agelim, hf;
                   6749:   double ***p3matp, ***p3matm, ***varhe;
                   6750:   double **dnewm,**doldm;
                   6751:   double *xp, *xm;
                   6752:   double **gp, **gm;
                   6753:   double ***gradg, ***trgradg;
                   6754:   int theta;
                   6755: 
                   6756:   double eip, vip;
                   6757: 
                   6758:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6759:   xp=vector(1,npar);
                   6760:   xm=vector(1,npar);
                   6761:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6762:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6763:   
                   6764:   pstamp(ficresstdeij);
                   6765:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6766:   fprintf(ficresstdeij,"# Age");
                   6767:   for(i=1; i<=nlstate;i++){
                   6768:     for(j=1; j<=nlstate;j++)
                   6769:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6770:     fprintf(ficresstdeij," e%1d. ",i);
                   6771:   }
                   6772:   fprintf(ficresstdeij,"\n");
                   6773: 
                   6774:   pstamp(ficrescveij);
                   6775:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6776:   fprintf(ficrescveij,"# Age");
                   6777:   for(i=1; i<=nlstate;i++)
                   6778:     for(j=1; j<=nlstate;j++){
                   6779:       cptj= (j-1)*nlstate+i;
                   6780:       for(i2=1; i2<=nlstate;i2++)
                   6781:        for(j2=1; j2<=nlstate;j2++){
                   6782:          cptj2= (j2-1)*nlstate+i2;
                   6783:          if(cptj2 <= cptj)
                   6784:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6785:        }
                   6786:     }
                   6787:   fprintf(ficrescveij,"\n");
                   6788:   
                   6789:   if(estepm < stepm){
                   6790:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6791:   }
                   6792:   else  hstepm=estepm;   
                   6793:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6794:    * This is mainly to measure the difference between two models: for example
                   6795:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6796:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6797:    * progression in between and thus overestimating or underestimating according
                   6798:    * to the curvature of the survival function. If, for the same date, we 
                   6799:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6800:    * to compare the new estimate of Life expectancy with the same linear 
                   6801:    * hypothesis. A more precise result, taking into account a more precise
                   6802:    * curvature will be obtained if estepm is as small as stepm. */
                   6803: 
                   6804:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6805:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6806:      nhstepm is the number of hstepm from age to agelim 
                   6807:      nstepm is the number of stepm from age to agelin. 
                   6808:      Look at hpijx to understand the reason of that which relies in memory size
                   6809:      and note for a fixed period like estepm months */
                   6810:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6811:      survival function given by stepm (the optimization length). Unfortunately it
                   6812:      means that if the survival funtion is printed only each two years of age and if
                   6813:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6814:      results. So we changed our mind and took the option of the best precision.
                   6815:   */
                   6816:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6817: 
                   6818:   /* If stepm=6 months */
                   6819:   /* nhstepm age range expressed in number of stepm */
                   6820:   agelim=AGESUP;
                   6821:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6822:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6823:   /* if (stepm >= YEARM) hstepm=1;*/
                   6824:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6825:   
                   6826:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6827:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6828:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6829:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6830:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6831:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6832: 
                   6833:   for (age=bage; age<=fage; age ++){ 
                   6834:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6835:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6836:     /* if (stepm >= YEARM) hstepm=1;*/
                   6837:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6838:                
1.126     brouard  6839:     /* If stepm=6 months */
                   6840:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6841:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6842:     
                   6843:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6844:                
1.126     brouard  6845:     /* Computing  Variances of health expectancies */
                   6846:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6847:        decrease memory allocation */
                   6848:     for(theta=1; theta <=npar; theta++){
                   6849:       for(i=1; i<=npar; i++){ 
1.222     brouard  6850:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6851:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6852:       }
1.235     brouard  6853:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6854:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6855:                        
1.126     brouard  6856:       for(j=1; j<= nlstate; j++){
1.222     brouard  6857:        for(i=1; i<=nlstate; i++){
                   6858:          for(h=0; h<=nhstepm-1; h++){
                   6859:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6860:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6861:          }
                   6862:        }
1.126     brouard  6863:       }
1.218     brouard  6864:                        
1.126     brouard  6865:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6866:        for(h=0; h<=nhstepm-1; h++){
                   6867:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6868:        }
1.126     brouard  6869:     }/* End theta */
                   6870:     
                   6871:     
                   6872:     for(h=0; h<=nhstepm-1; h++)
                   6873:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6874:        for(theta=1; theta <=npar; theta++)
                   6875:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6876:     
1.218     brouard  6877:                
1.222     brouard  6878:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6879:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6880:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6881:                
1.222     brouard  6882:     printf("%d|",(int)age);fflush(stdout);
                   6883:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6884:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6885:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6886:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6887:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6888:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6889:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6890:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6891:       }
                   6892:     }
1.320     brouard  6893:     /* if((int)age ==50){ */
                   6894:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6895:     /* } */
1.126     brouard  6896:     /* Computing expectancies */
1.235     brouard  6897:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6898:     for(i=1; i<=nlstate;i++)
                   6899:       for(j=1; j<=nlstate;j++)
1.222     brouard  6900:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6901:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6902:                                        
1.222     brouard  6903:          /* 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  6904:                                        
1.222     brouard  6905:        }
1.269     brouard  6906: 
                   6907:     /* Standard deviation of expectancies ij */                
1.126     brouard  6908:     fprintf(ficresstdeij,"%3.0f",age );
                   6909:     for(i=1; i<=nlstate;i++){
                   6910:       eip=0.;
                   6911:       vip=0.;
                   6912:       for(j=1; j<=nlstate;j++){
1.222     brouard  6913:        eip += eij[i][j][(int)age];
                   6914:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6915:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6916:        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  6917:       }
                   6918:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6919:     }
                   6920:     fprintf(ficresstdeij,"\n");
1.218     brouard  6921:                
1.269     brouard  6922:     /* Variance of expectancies ij */          
1.126     brouard  6923:     fprintf(ficrescveij,"%3.0f",age );
                   6924:     for(i=1; i<=nlstate;i++)
                   6925:       for(j=1; j<=nlstate;j++){
1.222     brouard  6926:        cptj= (j-1)*nlstate+i;
                   6927:        for(i2=1; i2<=nlstate;i2++)
                   6928:          for(j2=1; j2<=nlstate;j2++){
                   6929:            cptj2= (j2-1)*nlstate+i2;
                   6930:            if(cptj2 <= cptj)
                   6931:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6932:          }
1.126     brouard  6933:       }
                   6934:     fprintf(ficrescveij,"\n");
1.218     brouard  6935:                
1.126     brouard  6936:   }
                   6937:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6938:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6939:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6940:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6941:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6942:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6943:   printf("\n");
                   6944:   fprintf(ficlog,"\n");
1.218     brouard  6945:        
1.126     brouard  6946:   free_vector(xm,1,npar);
                   6947:   free_vector(xp,1,npar);
                   6948:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6949:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6950:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6951: }
1.218     brouard  6952:  
1.126     brouard  6953: /************ Variance ******************/
1.235     brouard  6954:  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  6955:  {
1.279     brouard  6956:    /** Variance of health expectancies 
                   6957:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6958:     * double **newm;
                   6959:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6960:     */
1.218     brouard  6961:   
                   6962:    /* int movingaverage(); */
                   6963:    double **dnewm,**doldm;
                   6964:    double **dnewmp,**doldmp;
                   6965:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6966:    int first=0;
1.218     brouard  6967:    int k;
                   6968:    double *xp;
1.279     brouard  6969:    double **gp, **gm;  /**< for var eij */
                   6970:    double ***gradg, ***trgradg; /**< for var eij */
                   6971:    double **gradgp, **trgradgp; /**< for var p point j */
                   6972:    double *gpp, *gmp; /**< for var p point j */
                   6973:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6974:    double ***p3mat;
                   6975:    double age,agelim, hf;
                   6976:    /* double ***mobaverage; */
                   6977:    int theta;
                   6978:    char digit[4];
                   6979:    char digitp[25];
                   6980: 
                   6981:    char fileresprobmorprev[FILENAMELENGTH];
                   6982: 
                   6983:    if(popbased==1){
                   6984:      if(mobilav!=0)
                   6985:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6986:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6987:    }
                   6988:    else 
                   6989:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6990: 
1.218     brouard  6991:    /* if (mobilav!=0) { */
                   6992:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6993:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6994:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6995:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6996:    /*   } */
                   6997:    /* } */
                   6998: 
                   6999:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7000:    sprintf(digit,"%-d",ij);
                   7001:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7002:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7003:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7004:    strcat(fileresprobmorprev,fileresu);
                   7005:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7006:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7007:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7008:    }
                   7009:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7010:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7011:    pstamp(ficresprobmorprev);
                   7012:    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  7013:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7014: 
                   7015:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7016:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7017:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7018:    /* } */
                   7019:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7020:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7021:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7022:    }
1.337     brouard  7023:    /* for(j=1;j<=cptcoveff;j++)  */
                   7024:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7025:    fprintf(ficresprobmorprev,"\n");
                   7026: 
1.218     brouard  7027:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7028:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7029:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7030:      for(i=1; i<=nlstate;i++)
                   7031:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7032:    }  
                   7033:    fprintf(ficresprobmorprev,"\n");
                   7034:   
                   7035:    fprintf(ficgp,"\n# Routine varevsij");
                   7036:    fprintf(ficgp,"\nunset title \n");
                   7037:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7038:    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");
                   7039:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7040: 
1.218     brouard  7041:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7042:    pstamp(ficresvij);
                   7043:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7044:    if(popbased==1)
                   7045:      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);
                   7046:    else
                   7047:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7048:    fprintf(ficresvij,"# Age");
                   7049:    for(i=1; i<=nlstate;i++)
                   7050:      for(j=1; j<=nlstate;j++)
                   7051:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7052:    fprintf(ficresvij,"\n");
                   7053: 
                   7054:    xp=vector(1,npar);
                   7055:    dnewm=matrix(1,nlstate,1,npar);
                   7056:    doldm=matrix(1,nlstate,1,nlstate);
                   7057:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7058:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7059: 
                   7060:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7061:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7062:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7063:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7064:   
1.218     brouard  7065:    if(estepm < stepm){
                   7066:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7067:    }
                   7068:    else  hstepm=estepm;   
                   7069:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7070:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7071:       nhstepm is the number of hstepm from age to agelim 
                   7072:       nstepm is the number of stepm from age to agelim. 
                   7073:       Look at function hpijx to understand why because of memory size limitations, 
                   7074:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7075:       survival function given by stepm (the optimization length). Unfortunately it
                   7076:       means that if the survival funtion is printed every two years of age and if
                   7077:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7078:       results. So we changed our mind and took the option of the best precision.
                   7079:    */
                   7080:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7081:    agelim = AGESUP;
                   7082:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7083:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7084:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7085:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7086:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7087:      gp=matrix(0,nhstepm,1,nlstate);
                   7088:      gm=matrix(0,nhstepm,1,nlstate);
                   7089:                
                   7090:                
                   7091:      for(theta=1; theta <=npar; theta++){
                   7092:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7093:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7094:        }
1.279     brouard  7095:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7096:        * returns into prlim .
1.288     brouard  7097:        */
1.242     brouard  7098:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7099: 
                   7100:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7101:        if (popbased==1) {
                   7102:         if(mobilav ==0){
                   7103:           for(i=1; i<=nlstate;i++)
                   7104:             prlim[i][i]=probs[(int)age][i][ij];
                   7105:         }else{ /* mobilav */ 
                   7106:           for(i=1; i<=nlstate;i++)
                   7107:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7108:         }
                   7109:        }
1.295     brouard  7110:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7111:        */                      
                   7112:        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  7113:        /**< 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  7114:        * at horizon h in state j including mortality.
                   7115:        */
1.218     brouard  7116:        for(j=1; j<= nlstate; j++){
                   7117:         for(h=0; h<=nhstepm; h++){
                   7118:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7119:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7120:         }
                   7121:        }
1.279     brouard  7122:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7123:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7124:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7125:        */
                   7126:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7127:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7128:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7129:        }
                   7130:        
                   7131:        /* Again with minus shift */
1.218     brouard  7132:                        
                   7133:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7134:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7135: 
1.242     brouard  7136:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7137:                        
                   7138:        if (popbased==1) {
                   7139:         if(mobilav ==0){
                   7140:           for(i=1; i<=nlstate;i++)
                   7141:             prlim[i][i]=probs[(int)age][i][ij];
                   7142:         }else{ /* mobilav */ 
                   7143:           for(i=1; i<=nlstate;i++)
                   7144:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7145:         }
                   7146:        }
                   7147:                        
1.235     brouard  7148:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7149:                        
                   7150:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7151:         for(h=0; h<=nhstepm; h++){
                   7152:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7153:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7154:         }
                   7155:        }
                   7156:        /* This for computing probability of death (h=1 means
                   7157:          computed over hstepm matrices product = hstepm*stepm months) 
                   7158:          as a weighted average of prlim.
                   7159:        */
                   7160:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7161:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7162:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7163:        }    
1.279     brouard  7164:        /* end shifting computations */
                   7165: 
                   7166:        /**< Computing gradient matrix at horizon h 
                   7167:        */
1.218     brouard  7168:        for(j=1; j<= nlstate; j++) /* vareij */
                   7169:         for(h=0; h<=nhstepm; h++){
                   7170:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7171:         }
1.279     brouard  7172:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7173:        */
                   7174:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7175:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7176:        }
                   7177:                        
                   7178:      } /* End theta */
1.279     brouard  7179:      
                   7180:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7181:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7182:                
                   7183:      for(h=0; h<=nhstepm; h++) /* veij */
                   7184:        for(j=1; j<=nlstate;j++)
                   7185:         for(theta=1; theta <=npar; theta++)
                   7186:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7187:                
                   7188:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7189:        for(theta=1; theta <=npar; theta++)
                   7190:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7191:      /**< as well as its transposed matrix 
                   7192:       */               
1.218     brouard  7193:                
                   7194:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7195:      for(i=1;i<=nlstate;i++)
                   7196:        for(j=1;j<=nlstate;j++)
                   7197:         vareij[i][j][(int)age] =0.;
1.279     brouard  7198: 
                   7199:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7200:       * and k (nhstepm) formula 15 of article
                   7201:       * Lievre-Brouard-Heathcote
                   7202:       */
                   7203:      
1.218     brouard  7204:      for(h=0;h<=nhstepm;h++){
                   7205:        for(k=0;k<=nhstepm;k++){
                   7206:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7207:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7208:         for(i=1;i<=nlstate;i++)
                   7209:           for(j=1;j<=nlstate;j++)
                   7210:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7211:        }
                   7212:      }
                   7213:                
1.279     brouard  7214:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7215:       * p.j overall mortality formula 49 but computed directly because
                   7216:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7217:       * wix is independent of theta.
                   7218:       */
1.218     brouard  7219:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7220:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7221:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7222:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7223:         varppt[j][i]=doldmp[j][i];
                   7224:      /* end ppptj */
                   7225:      /*  x centered again */
                   7226:                
1.242     brouard  7227:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7228:                
                   7229:      if (popbased==1) {
                   7230:        if(mobilav ==0){
                   7231:         for(i=1; i<=nlstate;i++)
                   7232:           prlim[i][i]=probs[(int)age][i][ij];
                   7233:        }else{ /* mobilav */ 
                   7234:         for(i=1; i<=nlstate;i++)
                   7235:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7236:        }
                   7237:      }
                   7238:                
                   7239:      /* This for computing probability of death (h=1 means
                   7240:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7241:        as a weighted average of prlim.
                   7242:      */
1.235     brouard  7243:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7244:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7245:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7246:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7247:      }    
                   7248:      /* end probability of death */
                   7249:                
                   7250:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7251:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7252:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7253:        for(i=1; i<=nlstate;i++){
                   7254:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7255:        }
                   7256:      } 
                   7257:      fprintf(ficresprobmorprev,"\n");
                   7258:                
                   7259:      fprintf(ficresvij,"%.0f ",age );
                   7260:      for(i=1; i<=nlstate;i++)
                   7261:        for(j=1; j<=nlstate;j++){
                   7262:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7263:        }
                   7264:      fprintf(ficresvij,"\n");
                   7265:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7266:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7267:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7268:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7269:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7270:    } /* End age */
                   7271:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7272:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7273:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7274:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7275:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7276:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7277:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7278:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7279:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7280:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7281:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7282:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7283:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7284:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7285:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7286:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7287:    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);
                   7288:    /*  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  7289:     */
1.218     brouard  7290:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7291:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7292: 
1.218     brouard  7293:    free_vector(xp,1,npar);
                   7294:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7295:    free_matrix(dnewm,1,nlstate,1,npar);
                   7296:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7297:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7298:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7299:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7300:    fclose(ficresprobmorprev);
                   7301:    fflush(ficgp);
                   7302:    fflush(fichtm); 
                   7303:  }  /* end varevsij */
1.126     brouard  7304: 
                   7305: /************ Variance of prevlim ******************/
1.269     brouard  7306:  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  7307: {
1.205     brouard  7308:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7309:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7310: 
1.268     brouard  7311:   double **dnewmpar,**doldm;
1.126     brouard  7312:   int i, j, nhstepm, hstepm;
                   7313:   double *xp;
                   7314:   double *gp, *gm;
                   7315:   double **gradg, **trgradg;
1.208     brouard  7316:   double **mgm, **mgp;
1.126     brouard  7317:   double age,agelim;
                   7318:   int theta;
                   7319:   
                   7320:   pstamp(ficresvpl);
1.288     brouard  7321:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7322:   fprintf(ficresvpl,"# Age ");
                   7323:   if(nresult >=1)
                   7324:     fprintf(ficresvpl," Result# ");
1.126     brouard  7325:   for(i=1; i<=nlstate;i++)
                   7326:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7327:   fprintf(ficresvpl,"\n");
                   7328: 
                   7329:   xp=vector(1,npar);
1.268     brouard  7330:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7331:   doldm=matrix(1,nlstate,1,nlstate);
                   7332:   
                   7333:   hstepm=1*YEARM; /* Every year of age */
                   7334:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7335:   agelim = AGESUP;
                   7336:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7337:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7338:     if (stepm >= YEARM) hstepm=1;
                   7339:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7340:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7341:     mgp=matrix(1,npar,1,nlstate);
                   7342:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7343:     gp=vector(1,nlstate);
                   7344:     gm=vector(1,nlstate);
                   7345: 
                   7346:     for(theta=1; theta <=npar; theta++){
                   7347:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7348:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7349:       }
1.288     brouard  7350:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7351:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7352:       /* else */
                   7353:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7354:       for(i=1;i<=nlstate;i++){
1.126     brouard  7355:        gp[i] = prlim[i][i];
1.208     brouard  7356:        mgp[theta][i] = prlim[i][i];
                   7357:       }
1.126     brouard  7358:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7359:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7360:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7361:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7362:       /* else */
                   7363:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7364:       for(i=1;i<=nlstate;i++){
1.126     brouard  7365:        gm[i] = prlim[i][i];
1.208     brouard  7366:        mgm[theta][i] = prlim[i][i];
                   7367:       }
1.126     brouard  7368:       for(i=1;i<=nlstate;i++)
                   7369:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7370:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7371:     } /* End theta */
                   7372: 
                   7373:     trgradg =matrix(1,nlstate,1,npar);
                   7374: 
                   7375:     for(j=1; j<=nlstate;j++)
                   7376:       for(theta=1; theta <=npar; theta++)
                   7377:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7378:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7379:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7380:     /*   for(j=1; j<=nlstate;j++){ */
                   7381:     /*         printf(" %d ",j); */
                   7382:     /*         for(theta=1; theta <=npar; theta++) */
                   7383:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7384:     /*         printf("\n "); */
                   7385:     /*   } */
                   7386:     /* } */
                   7387:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7388:     /*   printf("\n gradg %d ",(int)age); */
                   7389:     /*   for(j=1; j<=nlstate;j++){ */
                   7390:     /*         printf("%d ",j); */
                   7391:     /*         for(theta=1; theta <=npar; theta++) */
                   7392:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7393:     /*         printf("\n "); */
                   7394:     /*   } */
                   7395:     /* } */
1.126     brouard  7396: 
                   7397:     for(i=1;i<=nlstate;i++)
                   7398:       varpl[i][(int)age] =0.;
1.209     brouard  7399:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7400:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7401:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7402:     }else{
1.268     brouard  7403:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7404:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7405:     }
1.126     brouard  7406:     for(i=1;i<=nlstate;i++)
                   7407:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7408: 
                   7409:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7410:     if(nresult >=1)
                   7411:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7412:     for(i=1; i<=nlstate;i++){
1.126     brouard  7413:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7414:       /* for(j=1;j<=nlstate;j++) */
                   7415:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7416:     }
1.126     brouard  7417:     fprintf(ficresvpl,"\n");
                   7418:     free_vector(gp,1,nlstate);
                   7419:     free_vector(gm,1,nlstate);
1.208     brouard  7420:     free_matrix(mgm,1,npar,1,nlstate);
                   7421:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7422:     free_matrix(gradg,1,npar,1,nlstate);
                   7423:     free_matrix(trgradg,1,nlstate,1,npar);
                   7424:   } /* End age */
                   7425: 
                   7426:   free_vector(xp,1,npar);
                   7427:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7428:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7429: 
                   7430: }
                   7431: 
                   7432: 
                   7433: /************ Variance of backprevalence limit ******************/
1.269     brouard  7434:  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  7435: {
                   7436:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7437:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7438: 
                   7439:   double **dnewmpar,**doldm;
                   7440:   int i, j, nhstepm, hstepm;
                   7441:   double *xp;
                   7442:   double *gp, *gm;
                   7443:   double **gradg, **trgradg;
                   7444:   double **mgm, **mgp;
                   7445:   double age,agelim;
                   7446:   int theta;
                   7447:   
                   7448:   pstamp(ficresvbl);
                   7449:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7450:   fprintf(ficresvbl,"# Age ");
                   7451:   if(nresult >=1)
                   7452:     fprintf(ficresvbl," Result# ");
                   7453:   for(i=1; i<=nlstate;i++)
                   7454:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7455:   fprintf(ficresvbl,"\n");
                   7456: 
                   7457:   xp=vector(1,npar);
                   7458:   dnewmpar=matrix(1,nlstate,1,npar);
                   7459:   doldm=matrix(1,nlstate,1,nlstate);
                   7460:   
                   7461:   hstepm=1*YEARM; /* Every year of age */
                   7462:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7463:   agelim = AGEINF;
                   7464:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7465:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7466:     if (stepm >= YEARM) hstepm=1;
                   7467:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7468:     gradg=matrix(1,npar,1,nlstate);
                   7469:     mgp=matrix(1,npar,1,nlstate);
                   7470:     mgm=matrix(1,npar,1,nlstate);
                   7471:     gp=vector(1,nlstate);
                   7472:     gm=vector(1,nlstate);
                   7473: 
                   7474:     for(theta=1; theta <=npar; theta++){
                   7475:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7476:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7477:       }
                   7478:       if(mobilavproj > 0 )
                   7479:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7480:       else
                   7481:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7482:       for(i=1;i<=nlstate;i++){
                   7483:        gp[i] = bprlim[i][i];
                   7484:        mgp[theta][i] = bprlim[i][i];
                   7485:       }
                   7486:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7487:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7488:        if(mobilavproj > 0 )
                   7489:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7490:        else
                   7491:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7492:       for(i=1;i<=nlstate;i++){
                   7493:        gm[i] = bprlim[i][i];
                   7494:        mgm[theta][i] = bprlim[i][i];
                   7495:       }
                   7496:       for(i=1;i<=nlstate;i++)
                   7497:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7498:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7499:     } /* End theta */
                   7500: 
                   7501:     trgradg =matrix(1,nlstate,1,npar);
                   7502: 
                   7503:     for(j=1; j<=nlstate;j++)
                   7504:       for(theta=1; theta <=npar; theta++)
                   7505:        trgradg[j][theta]=gradg[theta][j];
                   7506:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7507:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7508:     /*   for(j=1; j<=nlstate;j++){ */
                   7509:     /*         printf(" %d ",j); */
                   7510:     /*         for(theta=1; theta <=npar; theta++) */
                   7511:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7512:     /*         printf("\n "); */
                   7513:     /*   } */
                   7514:     /* } */
                   7515:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7516:     /*   printf("\n gradg %d ",(int)age); */
                   7517:     /*   for(j=1; j<=nlstate;j++){ */
                   7518:     /*         printf("%d ",j); */
                   7519:     /*         for(theta=1; theta <=npar; theta++) */
                   7520:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7521:     /*         printf("\n "); */
                   7522:     /*   } */
                   7523:     /* } */
                   7524: 
                   7525:     for(i=1;i<=nlstate;i++)
                   7526:       varbpl[i][(int)age] =0.;
                   7527:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7528:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7529:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7530:     }else{
                   7531:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7532:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7533:     }
                   7534:     for(i=1;i<=nlstate;i++)
                   7535:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7536: 
                   7537:     fprintf(ficresvbl,"%.0f ",age );
                   7538:     if(nresult >=1)
                   7539:       fprintf(ficresvbl,"%d ",nres );
                   7540:     for(i=1; i<=nlstate;i++)
                   7541:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7542:     fprintf(ficresvbl,"\n");
                   7543:     free_vector(gp,1,nlstate);
                   7544:     free_vector(gm,1,nlstate);
                   7545:     free_matrix(mgm,1,npar,1,nlstate);
                   7546:     free_matrix(mgp,1,npar,1,nlstate);
                   7547:     free_matrix(gradg,1,npar,1,nlstate);
                   7548:     free_matrix(trgradg,1,nlstate,1,npar);
                   7549:   } /* End age */
                   7550: 
                   7551:   free_vector(xp,1,npar);
                   7552:   free_matrix(doldm,1,nlstate,1,npar);
                   7553:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7554: 
                   7555: }
                   7556: 
                   7557: /************ Variance of one-step probabilities  ******************/
                   7558: 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  7559:  {
                   7560:    int i, j=0,  k1, l1, tj;
                   7561:    int k2, l2, j1,  z1;
                   7562:    int k=0, l;
                   7563:    int first=1, first1, first2;
1.326     brouard  7564:    int nres=0; /* New */
1.222     brouard  7565:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7566:    double **dnewm,**doldm;
                   7567:    double *xp;
                   7568:    double *gp, *gm;
                   7569:    double **gradg, **trgradg;
                   7570:    double **mu;
                   7571:    double age, cov[NCOVMAX+1];
                   7572:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7573:    int theta;
                   7574:    char fileresprob[FILENAMELENGTH];
                   7575:    char fileresprobcov[FILENAMELENGTH];
                   7576:    char fileresprobcor[FILENAMELENGTH];
                   7577:    double ***varpij;
                   7578: 
                   7579:    strcpy(fileresprob,"PROB_"); 
                   7580:    strcat(fileresprob,fileres);
                   7581:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7582:      printf("Problem with resultfile: %s\n", fileresprob);
                   7583:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7584:    }
                   7585:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7586:    strcat(fileresprobcov,fileresu);
                   7587:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7588:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7589:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7590:    }
                   7591:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7592:    strcat(fileresprobcor,fileresu);
                   7593:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7594:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7595:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7596:    }
                   7597:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7598:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7599:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7600:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7601:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7602:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7603:    pstamp(ficresprob);
                   7604:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7605:    fprintf(ficresprob,"# Age");
                   7606:    pstamp(ficresprobcov);
                   7607:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7608:    fprintf(ficresprobcov,"# Age");
                   7609:    pstamp(ficresprobcor);
                   7610:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7611:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7612: 
                   7613: 
1.222     brouard  7614:    for(i=1; i<=nlstate;i++)
                   7615:      for(j=1; j<=(nlstate+ndeath);j++){
                   7616:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7617:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7618:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7619:      }  
                   7620:    /* fprintf(ficresprob,"\n");
                   7621:       fprintf(ficresprobcov,"\n");
                   7622:       fprintf(ficresprobcor,"\n");
                   7623:    */
                   7624:    xp=vector(1,npar);
                   7625:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7626:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7627:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7628:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7629:    first=1;
                   7630:    fprintf(ficgp,"\n# Routine varprob");
                   7631:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7632:    fprintf(fichtm,"\n");
                   7633: 
1.288     brouard  7634:    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  7635:    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);
                   7636:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7637: and drawn. It helps understanding how is the covariance between two incidences.\
                   7638:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7639:    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  7640: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7641: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7642: standard deviations wide on each axis. <br>\
                   7643:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7644:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7645: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7646: 
1.222     brouard  7647:    cov[1]=1;
                   7648:    /* tj=cptcoveff; */
1.225     brouard  7649:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7650:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7651:    j1=0;
1.332     brouard  7652: 
                   7653:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7654:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7655:      /* 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  7656:      if(tj != 1 && TKresult[nres]!= j1)
                   7657:        continue;
                   7658: 
                   7659:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7660:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7661:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7662:      if  (cptcovn>0) {
1.334     brouard  7663:        fprintf(ficresprob, "\n#********** Variable ");
                   7664:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7665:        fprintf(ficgp, "\n#********** Variable ");
                   7666:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7667:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7668: 
                   7669:        /* Including quantitative variables of the resultline to be done */
                   7670:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7671:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7672:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7673:         /* 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  7674:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7675:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7676:             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  */
                   7677:             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  */
                   7678:             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  */
                   7679:             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  */
                   7680:             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  */
                   7681:             fprintf(ficresprob,"fixed ");
                   7682:             fprintf(ficresprobcov,"fixed ");
                   7683:             fprintf(ficgp,"fixed ");
                   7684:             fprintf(fichtmcov,"fixed ");
                   7685:             fprintf(ficresprobcor,"fixed ");
                   7686:           }else{
                   7687:             fprintf(ficresprob,"varyi ");
                   7688:             fprintf(ficresprobcov,"varyi ");
                   7689:             fprintf(ficgp,"varyi ");
                   7690:             fprintf(fichtmcov,"varyi ");
                   7691:             fprintf(ficresprobcor,"varyi ");
                   7692:           }
                   7693:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7694:           /* For each selected (single) quantitative value */
1.337     brouard  7695:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7696:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7697:             fprintf(ficresprob,"fixed ");
                   7698:             fprintf(ficresprobcov,"fixed ");
                   7699:             fprintf(ficgp,"fixed ");
                   7700:             fprintf(fichtmcov,"fixed ");
                   7701:             fprintf(ficresprobcor,"fixed ");
                   7702:           }else{
                   7703:             fprintf(ficresprob,"varyi ");
                   7704:             fprintf(ficresprobcov,"varyi ");
                   7705:             fprintf(ficgp,"varyi ");
                   7706:             fprintf(fichtmcov,"varyi ");
                   7707:             fprintf(ficresprobcor,"varyi ");
                   7708:           }
                   7709:         }else{
                   7710:           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 */
                   7711:           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 */
                   7712:           exit(1);
                   7713:         }
                   7714:        } /* End loop on variable of this resultline */
                   7715:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7716:        fprintf(ficresprob, "**********\n#\n");
                   7717:        fprintf(ficresprobcov, "**********\n#\n");
                   7718:        fprintf(ficgp, "**********\n#\n");
                   7719:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7720:        fprintf(ficresprobcor, "**********\n#");    
                   7721:        if(invalidvarcomb[j1]){
                   7722:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7723:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7724:         continue;
                   7725:        }
                   7726:      }
                   7727:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7728:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7729:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7730:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7731:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7732:        cov[2]=age;
                   7733:        if(nagesqr==1)
                   7734:         cov[3]= age*age;
1.334     brouard  7735:        /* New code end of combination but for each resultline */
                   7736:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349   ! brouard  7737:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7738:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7739:         }else{
1.334     brouard  7740:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7741:         }
1.334     brouard  7742:        }/* End of loop on model equation */
                   7743: /* Old code */
                   7744:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7745:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7746:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7747:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7748:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7749:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7750:        /*                                                                  * 1  1 1 1 1 */
                   7751:        /*                                                                  * 2  2 1 1 1 */
                   7752:        /*                                                                  * 3  1 2 1 1 */
                   7753:        /*                                                                  *\/ */
                   7754:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7755:        /* } */
                   7756:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7757:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7758:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7759:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7760:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7761:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7762:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7763:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7764:        /*         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]); */
                   7765:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7766:        /*         /\* exit(1); *\/ */
                   7767:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7768:        /*       } */
                   7769:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7770:        /* } */
                   7771:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7772:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7773:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7774:        /*           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]])]; */
                   7775:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7776:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7777:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7778:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7779:        /*         } */
                   7780:        /*       }else{ */
                   7781:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7782:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7783:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7784:        /*         }else{ */
                   7785:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7786:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7787:        /*         } */
                   7788:        /*       } */
                   7789:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7790:        /* } */                 
1.326     brouard  7791: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7792:        for(theta=1; theta <=npar; theta++){
                   7793:         for(i=1; i<=npar; i++)
                   7794:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7795:                                
1.222     brouard  7796:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7797:                                
1.222     brouard  7798:         k=0;
                   7799:         for(i=1; i<= (nlstate); i++){
                   7800:           for(j=1; j<=(nlstate+ndeath);j++){
                   7801:             k=k+1;
                   7802:             gp[k]=pmmij[i][j];
                   7803:           }
                   7804:         }
1.220     brouard  7805:                                
1.222     brouard  7806:         for(i=1; i<=npar; i++)
                   7807:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7808:                                
1.222     brouard  7809:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7810:         k=0;
                   7811:         for(i=1; i<=(nlstate); i++){
                   7812:           for(j=1; j<=(nlstate+ndeath);j++){
                   7813:             k=k+1;
                   7814:             gm[k]=pmmij[i][j];
                   7815:           }
                   7816:         }
1.220     brouard  7817:                                
1.222     brouard  7818:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7819:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7820:        }
1.126     brouard  7821: 
1.222     brouard  7822:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7823:         for(theta=1; theta <=npar; theta++)
                   7824:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7825:                        
1.222     brouard  7826:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7827:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7828:                        
1.222     brouard  7829:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7830:                        
1.222     brouard  7831:        k=0;
                   7832:        for(i=1; i<=(nlstate); i++){
                   7833:         for(j=1; j<=(nlstate+ndeath);j++){
                   7834:           k=k+1;
                   7835:           mu[k][(int) age]=pmmij[i][j];
                   7836:         }
                   7837:        }
                   7838:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7839:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7840:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7841:                        
1.222     brouard  7842:        /*printf("\n%d ",(int)age);
                   7843:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7844:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7845:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7846:         }*/
1.220     brouard  7847:                        
1.222     brouard  7848:        fprintf(ficresprob,"\n%d ",(int)age);
                   7849:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7850:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7851:                        
1.222     brouard  7852:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7853:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7854:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7855:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7856:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7857:        }
                   7858:        i=0;
                   7859:        for (k=1; k<=(nlstate);k++){
                   7860:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7861:           i++;
                   7862:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7863:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7864:           for (j=1; j<=i;j++){
                   7865:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7866:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7867:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7868:           }
                   7869:         }
                   7870:        }/* end of loop for state */
                   7871:      } /* end of loop for age */
                   7872:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7873:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7874:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7875:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7876:     
                   7877:      /* Confidence intervalle of pij  */
                   7878:      /*
                   7879:        fprintf(ficgp,"\nunset parametric;unset label");
                   7880:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7881:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7882:        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);
                   7883:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7884:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7885:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7886:      */
                   7887:                
                   7888:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7889:      first1=1;first2=2;
                   7890:      for (k2=1; k2<=(nlstate);k2++){
                   7891:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7892:         if(l2==k2) continue;
                   7893:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7894:         for (k1=1; k1<=(nlstate);k1++){
                   7895:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7896:             if(l1==k1) continue;
                   7897:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7898:             if(i<=j) continue;
                   7899:             for (age=bage; age<=fage; age ++){ 
                   7900:               if ((int)age %5==0){
                   7901:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7902:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7903:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7904:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7905:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7906:                 c12=cv12/sqrt(v1*v2);
                   7907:                 /* Computing eigen value of matrix of covariance */
                   7908:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7909:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7910:                 if ((lc2 <0) || (lc1 <0) ){
                   7911:                   if(first2==1){
                   7912:                     first1=0;
                   7913:                     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);
                   7914:                   }
                   7915:                   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);
                   7916:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7917:                   /* lc2=fabs(lc2); */
                   7918:                 }
1.220     brouard  7919:                                                                
1.222     brouard  7920:                 /* Eigen vectors */
1.280     brouard  7921:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7922:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7923:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7924:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7925:                 }else
                   7926:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7927:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7928:                 v21=(lc1-v1)/cv12*v11;
                   7929:                 v12=-v21;
                   7930:                 v22=v11;
                   7931:                 tnalp=v21/v11;
                   7932:                 if(first1==1){
                   7933:                   first1=0;
                   7934:                   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);
                   7935:                 }
                   7936:                 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);
                   7937:                 /*printf(fignu*/
                   7938:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7939:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7940:                 if(first==1){
                   7941:                   first=0;
                   7942:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7943:                   fprintf(ficgp,"\nset parametric;unset label");
                   7944:                   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);
                   7945:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7946:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7947:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7948: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7949:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7950:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7951:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7952:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7953:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7954:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7955:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7956:                   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  7957:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7958:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7959:                 }else{
                   7960:                   first=0;
                   7961:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7962:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7963:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7964:                   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  7965:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7966:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7967:                 }/* if first */
                   7968:               } /* age mod 5 */
                   7969:             } /* end loop age */
                   7970:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7971:             first=1;
                   7972:           } /*l12 */
                   7973:         } /* k12 */
                   7974:        } /*l1 */
                   7975:      }/* k1 */
1.332     brouard  7976:    }  /* loop on combination of covariates j1 */
1.326     brouard  7977:    } /* loop on nres */
1.222     brouard  7978:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7979:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7980:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7981:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7982:    free_vector(xp,1,npar);
                   7983:    fclose(ficresprob);
                   7984:    fclose(ficresprobcov);
                   7985:    fclose(ficresprobcor);
                   7986:    fflush(ficgp);
                   7987:    fflush(fichtmcov);
                   7988:  }
1.126     brouard  7989: 
                   7990: 
                   7991: /******************* Printing html file ***********/
1.201     brouard  7992: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7993:                  int lastpass, int stepm, int weightopt, char model[],\
                   7994:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7995:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7996:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7997:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7998:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7999:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8000:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8001:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8002: </ul>");
1.319     brouard  8003: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8004: /* </ul>", model); */
1.214     brouard  8005:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8006:    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",
                   8007:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8008:    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  8009:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8010:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8011:    fprintf(fichtm,"\
                   8012:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8013:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8014:    fprintf(fichtm,"\
1.217     brouard  8015:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8016:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8017:    fprintf(fichtm,"\
1.288     brouard  8018:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8019:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8020:    fprintf(fichtm,"\
1.288     brouard  8021:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8022:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8023:    fprintf(fichtm,"\
1.211     brouard  8024:  - (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  8025:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8026:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8027:    if(prevfcast==1){
                   8028:      fprintf(fichtm,"\
                   8029:  - Prevalence projections by age and states:                           \
1.201     brouard  8030:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8031:    }
1.126     brouard  8032: 
                   8033: 
1.225     brouard  8034:    m=pow(2,cptcoveff);
1.222     brouard  8035:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8036: 
1.317     brouard  8037:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8038: 
                   8039:    jj1=0;
                   8040: 
                   8041:    fprintf(fichtm," \n<ul>");
1.337     brouard  8042:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8043:      /* k1=nres; */
1.338     brouard  8044:      k1=TKresult[nres];
                   8045:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8046:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8047:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8048:    /*     continue; */
1.264     brouard  8049:      jj1++;
                   8050:      if (cptcovn > 0) {
                   8051:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8052:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8053:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8054:        }
1.337     brouard  8055:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8056:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8057:        /* } */
                   8058:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8059:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8060:        /* } */
1.264     brouard  8061:        fprintf(fichtm,"\">");
                   8062:        
                   8063:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8064:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8065:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8066:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8067:        }
1.337     brouard  8068:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8069:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8070:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8071:        /* } */
                   8072:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8073:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8074:        /* } */
1.264     brouard  8075:        if(invalidvarcomb[k1]){
                   8076:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8077:         continue;
                   8078:        }
                   8079:        fprintf(fichtm,"</a></li>");
                   8080:      } /* cptcovn >0 */
                   8081:    }
1.317     brouard  8082:    fprintf(fichtm," \n</ul>");
1.264     brouard  8083: 
1.222     brouard  8084:    jj1=0;
1.237     brouard  8085: 
1.337     brouard  8086:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8087:      /* k1=nres; */
1.338     brouard  8088:      k1=TKresult[nres];
                   8089:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8090:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8091:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8092:    /*     continue; */
1.220     brouard  8093: 
1.222     brouard  8094:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8095:      jj1++;
                   8096:      if (cptcovn > 0) {
1.264     brouard  8097:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8098:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8099:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8100:        }
1.337     brouard  8101:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8102:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8103:        /* } */
1.264     brouard  8104:        fprintf(fichtm,"\"</a>");
                   8105:  
1.222     brouard  8106:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8107:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8108:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8109:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8110:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8111:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8112:        }
1.230     brouard  8113:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8114:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8115:        if(invalidvarcomb[k1]){
                   8116:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8117:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8118:         continue;
                   8119:        }
                   8120:      }
                   8121:      /* aij, bij */
1.259     brouard  8122:      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  8123: <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  8124:      /* Pij */
1.241     brouard  8125:      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> \
                   8126: <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  8127:      /* Quasi-incidences */
                   8128:      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  8129:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8130:  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  8131: 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> \
                   8132: <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  8133:      /* Survival functions (period) in state j */
                   8134:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8135:        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);
                   8136:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8137:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8138:      }
                   8139:      /* State specific survival functions (period) */
                   8140:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8141:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8142:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8143:  <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);
                   8144:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8145:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8146:      }
1.288     brouard  8147:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8148:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8149:        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  8150:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8151:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8152:      }
1.296     brouard  8153:      if(prevbcast==1){
1.288     brouard  8154:        /* Backward prevalence in each health state */
1.222     brouard  8155:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8156:         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);
                   8157:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8158:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8159:        }
1.217     brouard  8160:      }
1.222     brouard  8161:      if(prevfcast==1){
1.288     brouard  8162:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8163:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8164:         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);
                   8165:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8166:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8167:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8168:        }
                   8169:      }
1.296     brouard  8170:      if(prevbcast==1){
1.268     brouard  8171:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8172:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8173:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8174:  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 \
                   8175:  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  8176: 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);
                   8177:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8178:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8179:        }
                   8180:      }
1.220     brouard  8181:         
1.222     brouard  8182:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8183:        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);
                   8184:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8185:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8186:      }
                   8187:      /* } /\* end i1 *\/ */
1.337     brouard  8188:    }/* End k1=nres */
1.222     brouard  8189:    fprintf(fichtm,"</ul>");
1.126     brouard  8190: 
1.222     brouard  8191:    fprintf(fichtm,"\
1.126     brouard  8192: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8193:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8194:  - 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  8195: But because parameters are usually highly correlated (a higher incidence of disability \
                   8196: and a higher incidence of recovery can give very close observed transition) it might \
                   8197: be very useful to look not only at linear confidence intervals estimated from the \
                   8198: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8199: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8200: covariance matrix of the one-step probabilities. \
                   8201: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8202: 
1.222     brouard  8203:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8204:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8205:    fprintf(fichtm,"\
1.126     brouard  8206:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8207:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8208: 
1.222     brouard  8209:    fprintf(fichtm,"\
1.126     brouard  8210:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8211:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8212:    fprintf(fichtm,"\
1.126     brouard  8213:  - 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): \
                   8214:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8215:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8216:    fprintf(fichtm,"\
1.126     brouard  8217:  - (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): \
                   8218:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8219:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8220:    fprintf(fichtm,"\
1.288     brouard  8221:  - 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  8222:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8223:    fprintf(fichtm,"\
1.128     brouard  8224:  - 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  8225:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8226:    fprintf(fichtm,"\
1.288     brouard  8227:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8228:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8229: 
                   8230: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8231: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8232: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8233: /*     <br>",fileres,fileres,fileres,fileres); */
                   8234: /*  else  */
1.338     brouard  8235: /*    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  8236:    fflush(fichtm);
1.126     brouard  8237: 
1.225     brouard  8238:    m=pow(2,cptcoveff);
1.222     brouard  8239:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8240: 
1.317     brouard  8241:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8242: 
                   8243:   jj1=0;
                   8244: 
                   8245:    fprintf(fichtm," \n<ul>");
1.337     brouard  8246:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8247:      /* k1=nres; */
1.338     brouard  8248:      k1=TKresult[nres];
1.337     brouard  8249:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8250:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8251:      /*   continue; */
1.317     brouard  8252:      jj1++;
                   8253:      if (cptcovn > 0) {
                   8254:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8255:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8256:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8257:        }
                   8258:        fprintf(fichtm,"\">");
                   8259:        
                   8260:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8261:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8262:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8263:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8264:        }
                   8265:        if(invalidvarcomb[k1]){
                   8266:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8267:         continue;
                   8268:        }
                   8269:        fprintf(fichtm,"</a></li>");
                   8270:      } /* cptcovn >0 */
1.337     brouard  8271:    } /* End nres */
1.317     brouard  8272:    fprintf(fichtm," \n</ul>");
                   8273: 
1.222     brouard  8274:    jj1=0;
1.237     brouard  8275: 
1.241     brouard  8276:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8277:      /* k1=nres; */
1.338     brouard  8278:      k1=TKresult[nres];
                   8279:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8280:      /* for(k1=1; k1<=m;k1++){ */
                   8281:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8282:      /*   continue; */
1.222     brouard  8283:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8284:      jj1++;
1.126     brouard  8285:      if (cptcovn > 0) {
1.317     brouard  8286:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8287:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8288:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8289:        }
                   8290:        fprintf(fichtm,"\"</a>");
                   8291:        
1.126     brouard  8292:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8293:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8294:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8295:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8296:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8297:        }
1.237     brouard  8298: 
1.338     brouard  8299:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8300: 
1.222     brouard  8301:        if(invalidvarcomb[k1]){
                   8302:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8303:         continue;
                   8304:        }
1.337     brouard  8305:      } /* If cptcovn >0 */
1.126     brouard  8306:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8307:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8308: 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);
                   8309:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8310:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8311:      }
                   8312:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8313: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8314: true period expectancies (those weighted with period prevalences are also\
                   8315:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8316:  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);
                   8317:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8318:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8319:      /* } /\* end i1 *\/ */
1.241     brouard  8320:   }/* End nres */
1.222     brouard  8321:    fprintf(fichtm,"</ul>");
                   8322:    fflush(fichtm);
1.126     brouard  8323: }
                   8324: 
                   8325: /******************* Gnuplot file **************/
1.296     brouard  8326: 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  8327: 
                   8328:   char dirfileres[132],optfileres[132];
1.264     brouard  8329:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8330:   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  8331:   int lv=0, vlv=0, kl=0;
1.130     brouard  8332:   int ng=0;
1.201     brouard  8333:   int vpopbased;
1.223     brouard  8334:   int ioffset; /* variable offset for columns */
1.270     brouard  8335:   int iyearc=1; /* variable column for year of projection  */
                   8336:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8337:   int nres=0; /* Index of resultline */
1.266     brouard  8338:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8339: 
1.126     brouard  8340: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8341: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8342: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8343: /*   } */
                   8344: 
                   8345:   /*#ifdef windows */
                   8346:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8347:   /*#endif */
1.225     brouard  8348:   m=pow(2,cptcoveff);
1.126     brouard  8349: 
1.274     brouard  8350:   /* diagram of the model */
                   8351:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8352:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8353:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8354:   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);
                   8355: 
1.343     brouard  8356:   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  8357:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8358:   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);
                   8359:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8360:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8361:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8362:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8363: 
1.202     brouard  8364:   /* Contribution to likelihood */
                   8365:   /* Plot the probability implied in the likelihood */
1.223     brouard  8366:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8367:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8368:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8369:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8370: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8371:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8372: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8373:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8374:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8375:   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));
                   8376:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8377:   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));
                   8378:   for (i=1; i<= nlstate ; i ++) {
                   8379:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8380:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8381:     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);
                   8382:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8383:       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);
                   8384:     }
                   8385:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8386:   }
                   8387:   /* 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 */               
                   8388:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8389:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8390:   fprintf(ficgp,"\nset out;unset log\n");
                   8391:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8392: 
1.343     brouard  8393:   /* Plot the probability implied in the likelihood by covariate value */
                   8394:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8395:   /* if(debugILK==1){ */
                   8396:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8397:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8398:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
                   8399:     k=18+kf;/*offset because there are 18 columns in the ILK_ file */
1.343     brouard  8400:     for (i=1; i<= nlstate ; i ++) {
                   8401:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8402:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8403:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8404:        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);
                   8405:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8406:          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);
                   8407:        }
                   8408:       }else{
                   8409:        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);
                   8410:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8411:          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);
                   8412:        }
1.343     brouard  8413:       }
                   8414:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8415:     }
                   8416:   } /* End of each covariate dummy */
                   8417:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8418:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8419:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8420:      *  varying                   1     2                                 3       4        5
                   8421:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8422:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8423:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8424:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8425:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8426:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8427:      */
                   8428:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8429:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8430:     /* 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]); */
                   8431:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8432:       /* printf(" %d",ipos); */
                   8433:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8434:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8435:       kk++; /* Position of the ncovv column in ILK_ */
                   8436:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8437:       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)  */
                   8438:        for (i=1; i<= nlstate ; i ++) {
                   8439:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8440:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8441: 
1.348     brouard  8442:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8443:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8444:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8445:            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);
                   8446:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8447:              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);
                   8448:            }
                   8449:          }else{
                   8450:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8451:            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);
                   8452:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8453:              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);
                   8454:            }
                   8455:          }
                   8456:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8457:        }
                   8458:       }/* End if dummy varying */
                   8459:     }else{ /*Product */
                   8460:       /* printf("*"); */
                   8461:       /* fprintf(ficresilk,"*"); */
                   8462:     }
                   8463:     iposold=ipos;
                   8464:   } /* For each time varying covariate */
                   8465:   /* } /\* debugILK==1 *\/ */
                   8466:   /* 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 */               
                   8467:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8468:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8469:   fprintf(ficgp,"\nset out;unset log\n");
                   8470:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8471: 
                   8472: 
                   8473:   
1.126     brouard  8474:   strcpy(dirfileres,optionfilefiname);
                   8475:   strcpy(optfileres,"vpl");
1.223     brouard  8476:   /* 1eme*/
1.238     brouard  8477:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8478:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8479:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8480:        k1=TKresult[nres];
1.338     brouard  8481:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8482:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8483:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8484:        /*   continue; */
1.238     brouard  8485:        /* We are interested in selected combination by the resultline */
1.246     brouard  8486:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8487:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8488:        strcpy(gplotlabel,"(");
1.337     brouard  8489:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8490:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8491:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8492: 
                   8493:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8494:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8495:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8496:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8497:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8498:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8499:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8500:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8501:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8502:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8503:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8504:        /* } */
                   8505:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8506:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8507:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8508:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8509:        }
                   8510:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8511:        /* printf("\n#\n"); */
1.238     brouard  8512:        fprintf(ficgp,"\n#\n");
                   8513:        if(invalidvarcomb[k1]){
1.260     brouard  8514:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8515:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8516:          continue;
                   8517:        }
1.235     brouard  8518:       
1.241     brouard  8519:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8520:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8521:        /* 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  8522:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8523:        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);
                   8524:        /* 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); */
                   8525:       /* k1-1 error should be nres-1*/
1.238     brouard  8526:        for (i=1; i<= nlstate ; i ++) {
                   8527:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8528:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8529:        }
1.288     brouard  8530:        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  8531:        for (i=1; i<= nlstate ; i ++) {
                   8532:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8533:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8534:        } 
1.260     brouard  8535:        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  8536:        for (i=1; i<= nlstate ; i ++) {
                   8537:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8538:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8539:        }  
1.265     brouard  8540:        /* 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)); */
                   8541:        
                   8542:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8543:         if(cptcoveff ==0){
1.271     brouard  8544:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8545:        }else{
                   8546:          kl=0;
                   8547:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8548:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8549:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8550:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8551:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8552:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8553:            vlv= nbcode[Tvaraff[k]][lv];
                   8554:            kl++;
                   8555:            /* 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 *\/ */
                   8556:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8557:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8558:            /* ''  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*/
                   8559:            if(k==cptcoveff){
                   8560:              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], \
                   8561:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8562:            }else{
                   8563:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8564:              kl++;
                   8565:            }
                   8566:          } /* end covariate */
                   8567:        } /* end if no covariate */
                   8568: 
1.296     brouard  8569:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8570:          /* 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  8571:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8572:          if(cptcoveff ==0){
1.245     brouard  8573:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8574:          }else{
                   8575:            kl=0;
                   8576:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8577:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8578:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8579:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8580:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8581:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8582:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8583:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8584:              kl++;
1.238     brouard  8585:              /* 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 *\/ */
                   8586:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8587:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8588:              /* ''  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*/
                   8589:              if(k==cptcoveff){
1.245     brouard  8590:                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  8591:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8592:              }else{
1.332     brouard  8593:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8594:                kl++;
                   8595:              }
                   8596:            } /* end covariate */
                   8597:          } /* end if no covariate */
1.296     brouard  8598:          if(prevbcast == 1){
1.268     brouard  8599:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8600:            /* k1-1 error should be nres-1*/
                   8601:            for (i=1; i<= nlstate ; i ++) {
                   8602:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8603:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8604:            }
1.271     brouard  8605:            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  8606:            for (i=1; i<= nlstate ; i ++) {
                   8607:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8608:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8609:            } 
1.276     brouard  8610:            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  8611:            for (i=1; i<= nlstate ; i ++) {
                   8612:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8613:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8614:            } 
1.274     brouard  8615:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8616:          } /* end if backprojcast */
1.296     brouard  8617:        } /* end if prevbcast */
1.276     brouard  8618:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8619:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8620:       } /* nres */
1.337     brouard  8621:     /* } /\* k1 *\/ */
1.201     brouard  8622:   } /* cpt */
1.235     brouard  8623: 
                   8624:   
1.126     brouard  8625:   /*2 eme*/
1.337     brouard  8626:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8627:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8628:       k1=TKresult[nres];
1.338     brouard  8629:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8630:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8631:       /*       continue; */
1.238     brouard  8632:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8633:       strcpy(gplotlabel,"(");
1.337     brouard  8634:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8635:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8636:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8637:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8638:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8639:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8640:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8641:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8642:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8643:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8644:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8645:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8646:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8647:       /* } */
                   8648:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8649:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8650:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8651:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8652:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8653:       }
1.264     brouard  8654:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8655:       fprintf(ficgp,"\n#\n");
1.223     brouard  8656:       if(invalidvarcomb[k1]){
                   8657:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8658:        continue;
                   8659:       }
1.219     brouard  8660:                        
1.241     brouard  8661:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8662:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8663:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8664:        if(vpopbased==0){
1.238     brouard  8665:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8666:        }else
1.238     brouard  8667:          fprintf(ficgp,"\nreplot ");
                   8668:        for (i=1; i<= nlstate+1 ; i ++) {
                   8669:          k=2*i;
1.261     brouard  8670:          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  8671:          for (j=1; j<= nlstate+1 ; j ++) {
                   8672:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8673:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8674:          }   
                   8675:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8676:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8677:          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  8678:          for (j=1; j<= nlstate+1 ; j ++) {
                   8679:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8680:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8681:          }   
                   8682:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8683:          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  8684:          for (j=1; j<= nlstate+1 ; j ++) {
                   8685:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8686:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8687:          }   
                   8688:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8689:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8690:        } /* state */
                   8691:       } /* vpopbased */
1.264     brouard  8692:       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  8693:     } /* end nres */
1.337     brouard  8694:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8695:        
                   8696:        
                   8697:   /*3eme*/
1.337     brouard  8698:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8699:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8700:       k1=TKresult[nres];
1.338     brouard  8701:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8702:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8703:       /*       continue; */
1.238     brouard  8704: 
1.332     brouard  8705:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8706:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8707:        strcpy(gplotlabel,"(");
1.337     brouard  8708:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8709:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8710:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8711:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8712:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8713:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8714:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8715:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8716:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8717:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8718:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8719:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8720:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8721:        /* } */
                   8722:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8723:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8724:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8725:        }
1.264     brouard  8726:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8727:        fprintf(ficgp,"\n#\n");
                   8728:        if(invalidvarcomb[k1]){
                   8729:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8730:          continue;
                   8731:        }
                   8732:                        
                   8733:        /*       k=2+nlstate*(2*cpt-2); */
                   8734:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8735:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8736:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8737:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8738: 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  8739:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8740:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8741:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8742:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8743:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8744:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8745:                                
1.238     brouard  8746:        */
                   8747:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8748:          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  8749:          /*    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  8750:                                
1.238     brouard  8751:        } 
1.261     brouard  8752:        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  8753:       }
1.264     brouard  8754:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8755:     } /* end nres */
1.337     brouard  8756:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8757:   
1.223     brouard  8758:   /* 4eme */
1.201     brouard  8759:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8760:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8761:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8762:       k1=TKresult[nres];
1.338     brouard  8763:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8764:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8765:       /*       continue; */
1.238     brouard  8766:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8767:        strcpy(gplotlabel,"(");
1.337     brouard  8768:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8769:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8770:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8771:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8772:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8773:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8774:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8775:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8776:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8777:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8778:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8779:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8780:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8781:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8782:        /* } */
                   8783:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8784:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8785:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8786:        }       
1.264     brouard  8787:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8788:        fprintf(ficgp,"\n#\n");
                   8789:        if(invalidvarcomb[k1]){
                   8790:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8791:          continue;
1.223     brouard  8792:        }
1.238     brouard  8793:       
1.241     brouard  8794:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8795:        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  8796:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8797: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8798:        k=3;
                   8799:        for (i=1; i<= nlstate ; i ++){
                   8800:          if(i==1){
                   8801:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8802:          }else{
                   8803:            fprintf(ficgp,", '' ");
                   8804:          }
                   8805:          l=(nlstate+ndeath)*(i-1)+1;
                   8806:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8807:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8808:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8809:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8810:        } /* nlstate */
1.264     brouard  8811:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8812:       } /* end cpt state*/ 
                   8813:     } /* end nres */
1.337     brouard  8814:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8815: 
1.220     brouard  8816: /* 5eme */
1.201     brouard  8817:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8818:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8819:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8820:       k1=TKresult[nres];
1.338     brouard  8821:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8822:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8823:       /*       continue; */
1.238     brouard  8824:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8825:        strcpy(gplotlabel,"(");
1.238     brouard  8826:        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  8827:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8828:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8829:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8830:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8831:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8832:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8833:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8834:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8835:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8836:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8837:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8838:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8839:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8840:        /* } */
                   8841:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8842:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8843:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8844:        }       
1.264     brouard  8845:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8846:        fprintf(ficgp,"\n#\n");
                   8847:        if(invalidvarcomb[k1]){
                   8848:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8849:          continue;
                   8850:        }
1.227     brouard  8851:       
1.241     brouard  8852:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8853:        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  8854:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8855: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8856:        k=3;
                   8857:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8858:          if(j==1)
                   8859:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8860:          else
                   8861:            fprintf(ficgp,", '' ");
                   8862:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8863:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8864:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8865:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8866:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8867:        } /* nlstate */
                   8868:        fprintf(ficgp,", '' ");
                   8869:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8870:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8871:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8872:          if(j < nlstate)
                   8873:            fprintf(ficgp,"$%d +",k+l);
                   8874:          else
                   8875:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8876:        }
1.264     brouard  8877:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8878:       } /* end cpt state*/ 
1.337     brouard  8879:     /* } /\* end covariate *\/   */
1.238     brouard  8880:   } /* end nres */
1.227     brouard  8881:   
1.220     brouard  8882: /* 6eme */
1.202     brouard  8883:   /* CV preval stable (period) for each covariate */
1.337     brouard  8884:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8885:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8886:      k1=TKresult[nres];
1.338     brouard  8887:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8888:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8889:      /*  continue; */
1.255     brouard  8890:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8891:       strcpy(gplotlabel,"(");      
1.288     brouard  8892:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8893:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8894:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8895:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8896:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8897:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8898:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8899:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8900:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8901:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8902:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8903:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8904:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8905:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8906:       /* } */
                   8907:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8908:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8909:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8910:       }        
1.264     brouard  8911:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8912:       fprintf(ficgp,"\n#\n");
1.223     brouard  8913:       if(invalidvarcomb[k1]){
1.227     brouard  8914:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8915:        continue;
1.223     brouard  8916:       }
1.227     brouard  8917:       
1.241     brouard  8918:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8919:       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  8920:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8921: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8922:       k=3; /* Offset */
1.255     brouard  8923:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8924:        if(i==1)
                   8925:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8926:        else
                   8927:          fprintf(ficgp,", '' ");
1.255     brouard  8928:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8929:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8930:        for (j=2; j<= nlstate ; j ++)
                   8931:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8932:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8933:       } /* nlstate */
1.264     brouard  8934:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8935:     } /* end cpt state*/ 
                   8936:   } /* end covariate */  
1.227     brouard  8937:   
                   8938:   
1.220     brouard  8939: /* 7eme */
1.296     brouard  8940:   if(prevbcast == 1){
1.288     brouard  8941:     /* CV backward prevalence  for each covariate */
1.337     brouard  8942:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8943:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8944:       k1=TKresult[nres];
1.338     brouard  8945:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8946:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8947:       /*       continue; */
1.268     brouard  8948:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8949:        strcpy(gplotlabel,"(");      
1.288     brouard  8950:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8951:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8952:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8953:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8954:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8955:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8956:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8957:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8958:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8959:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8960:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8961:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8962:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8963:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8964:        /* } */
                   8965:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8966:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8967:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8968:        }       
1.264     brouard  8969:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8970:        fprintf(ficgp,"\n#\n");
                   8971:        if(invalidvarcomb[k1]){
                   8972:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8973:          continue;
                   8974:        }
                   8975:        
1.241     brouard  8976:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8977:        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  8978:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8979: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8980:        k=3; /* Offset */
1.268     brouard  8981:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8982:          if(i==1)
                   8983:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8984:          else
                   8985:            fprintf(ficgp,", '' ");
                   8986:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8987:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8988:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8989:          /* 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  8990:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8991:          /* for (j=2; j<= nlstate ; j ++) */
                   8992:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8993:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8994:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8995:        } /* nlstate */
1.264     brouard  8996:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8997:       } /* end cpt state*/ 
                   8998:     } /* end covariate */  
1.296     brouard  8999:   } /* End if prevbcast */
1.218     brouard  9000:   
1.223     brouard  9001:   /* 8eme */
1.218     brouard  9002:   if(prevfcast==1){
1.288     brouard  9003:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9004:     
1.337     brouard  9005:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9006:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9007:       k1=TKresult[nres];
1.338     brouard  9008:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9009:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9010:       /*       continue; */
1.211     brouard  9011:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9012:        strcpy(gplotlabel,"(");      
1.288     brouard  9013:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9014:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9015:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9016:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9017:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9018:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9019:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9020:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9021:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9022:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9023:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9024:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9025:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9026:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9027:        /* } */
                   9028:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9029:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9030:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9031:        }       
1.264     brouard  9032:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9033:        fprintf(ficgp,"\n#\n");
                   9034:        if(invalidvarcomb[k1]){
                   9035:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9036:          continue;
                   9037:        }
                   9038:        
                   9039:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9040:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9041:        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  9042:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9043: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9044: 
                   9045:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9046:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9047:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9048:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9049:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9050:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9051:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9052:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9053:          if(i==istart){
1.227     brouard  9054:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9055:          }else{
                   9056:            fprintf(ficgp,",\\\n '' ");
                   9057:          }
                   9058:          if(cptcoveff ==0){ /* No covariate */
                   9059:            ioffset=2; /* Age is in 2 */
                   9060:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9061:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9062:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9063:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9064:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9065:            if(i==nlstate+1){
1.270     brouard  9066:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9067:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9068:              fprintf(ficgp,",\\\n '' ");
                   9069:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9070:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9071:                     offyear,                           \
1.268     brouard  9072:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9073:            }else
1.227     brouard  9074:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9075:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9076:          }else{ /* more than 2 covariates */
1.270     brouard  9077:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9078:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9079:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9080:            iyearc=ioffset-1;
                   9081:            iagec=ioffset;
1.227     brouard  9082:            fprintf(ficgp," u %d:(",ioffset); 
                   9083:            kl=0;
                   9084:            strcpy(gplotcondition,"(");
                   9085:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  9086:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9087:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  9088:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9089:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9090:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9091:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9092:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  9093:              kl++;
                   9094:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   9095:              kl++;
                   9096:              if(k <cptcoveff && cptcoveff>1)
                   9097:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9098:            }
                   9099:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9100:            /* 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 *\/ */
                   9101:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9102:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9103:            /* ''  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*/
                   9104:            if(i==nlstate+1){
1.270     brouard  9105:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9106:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9107:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9108:              fprintf(ficgp," u %d:(",iagec); 
                   9109:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9110:                      iyearc, iagec, offyear,                           \
                   9111:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9112: /*  '' 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  9113:            }else{
                   9114:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9115:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9116:            }
                   9117:          } /* end if covariate */
                   9118:        } /* nlstate */
1.264     brouard  9119:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9120:       } /* end cpt state*/
                   9121:     } /* end covariate */
                   9122:   } /* End if prevfcast */
1.227     brouard  9123:   
1.296     brouard  9124:   if(prevbcast==1){
1.268     brouard  9125:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9126:     
1.337     brouard  9127:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9128:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9129:      k1=TKresult[nres];
1.338     brouard  9130:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9131:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9132:        /*      continue; */
1.268     brouard  9133:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9134:        strcpy(gplotlabel,"(");      
                   9135:        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  9136:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   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:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9140:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9141:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9142:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9143:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9144:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9145:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9146:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9147:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9148:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9149:        /* } */
                   9150:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9151:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9152:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9153:        }       
                   9154:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9155:        fprintf(ficgp,"\n#\n");
                   9156:        if(invalidvarcomb[k1]){
                   9157:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9158:          continue;
                   9159:        }
                   9160:        
                   9161:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9162:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9163:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9164:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9165: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9166: 
                   9167:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9168:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9169:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9170:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9171:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9172:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9173:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9174:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9175:          if(i==istart){
                   9176:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9177:          }else{
                   9178:            fprintf(ficgp,",\\\n '' ");
                   9179:          }
                   9180:          if(cptcoveff ==0){ /* No covariate */
                   9181:            ioffset=2; /* Age is in 2 */
                   9182:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9183:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9184:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9185:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9186:            fprintf(ficgp," u %d:(", ioffset); 
                   9187:            if(i==nlstate+1){
1.270     brouard  9188:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9189:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9190:              fprintf(ficgp,",\\\n '' ");
                   9191:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9192:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9193:                     offbyear,                          \
                   9194:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9195:            }else
                   9196:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9197:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9198:          }else{ /* more than 2 covariates */
1.270     brouard  9199:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9200:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9201:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9202:            iyearc=ioffset-1;
                   9203:            iagec=ioffset;
1.268     brouard  9204:            fprintf(ficgp," u %d:(",ioffset); 
                   9205:            kl=0;
                   9206:            strcpy(gplotcondition,"(");
1.337     brouard  9207:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9208:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9209:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9210:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9211:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9212:                lv=Tvresult[nres][k];
                   9213:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9214:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9215:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9216:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9217:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9218:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9219:                kl++;
                   9220:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9221:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9222:                kl++;
1.338     brouard  9223:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9224:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9225:              }
1.268     brouard  9226:            }
                   9227:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9228:            /* 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 *\/ */
                   9229:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9230:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9231:            /* ''  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*/
                   9232:            if(i==nlstate+1){
1.270     brouard  9233:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9234:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9235:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9236:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9237:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9238:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9239:                      iyearc,iagec,offbyear,                            \
                   9240:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9241: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9242:            }else{
                   9243:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9244:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9245:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9246:            }
                   9247:          } /* end if covariate */
                   9248:        } /* nlstate */
                   9249:        fprintf(ficgp,"\nset out; unset label;\n");
                   9250:       } /* end cpt state*/
                   9251:     } /* end covariate */
1.296     brouard  9252:   } /* End if prevbcast */
1.268     brouard  9253:   
1.227     brouard  9254:   
1.238     brouard  9255:   /* 9eme writing MLE parameters */
                   9256:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9257:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9258:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9259:     for(k=1; k <=(nlstate+ndeath); k++){
                   9260:       if (k != i) {
1.227     brouard  9261:        fprintf(ficgp,"#   current state %d\n",k);
                   9262:        for(j=1; j <=ncovmodel; j++){
                   9263:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9264:          jk++; 
                   9265:        }
                   9266:        fprintf(ficgp,"\n");
1.126     brouard  9267:       }
                   9268:     }
1.223     brouard  9269:   }
1.187     brouard  9270:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9271:   
1.145     brouard  9272:   /*goto avoid;*/
1.238     brouard  9273:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9274:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9275:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9276:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9277:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9278:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9279:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9280:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9281:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9282:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9283:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9284:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9285:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9286:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9287:   fprintf(ficgp,"#\n");
1.223     brouard  9288:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9289:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9290:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9291:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9292:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9293:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9294:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9295:      /* k1=nres; */
1.338     brouard  9296:       k1=TKresult[nres];
                   9297:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9298:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9299:       strcpy(gplotlabel,"(");
1.276     brouard  9300:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9301:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9302:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9303:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9304:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9305:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9306:       }
                   9307:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9308:       /*       continue; */
                   9309:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9310:       /* strcpy(gplotlabel,"("); */
                   9311:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9312:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9313:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9314:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9315:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9316:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9317:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9318:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9319:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9320:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9321:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9322:       /* } */
                   9323:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9324:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9325:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9326:       /* }      */
1.264     brouard  9327:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9328:       fprintf(ficgp,"\n#\n");
1.264     brouard  9329:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9330:       fprintf(ficgp,"\nset key outside ");
                   9331:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9332:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9333:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9334:       if (ng==1){
                   9335:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9336:        fprintf(ficgp,"\nunset log y");
                   9337:       }else if (ng==2){
                   9338:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9339:        fprintf(ficgp,"\nset log y");
                   9340:       }else if (ng==3){
                   9341:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9342:        fprintf(ficgp,"\nset log y");
                   9343:       }else
                   9344:        fprintf(ficgp,"\nunset title ");
                   9345:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9346:       i=1;
                   9347:       for(k2=1; k2<=nlstate; k2++) {
                   9348:        k3=i;
                   9349:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9350:          if (k != k2){
                   9351:            switch( ng) {
                   9352:            case 1:
                   9353:              if(nagesqr==0)
                   9354:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9355:              else /* nagesqr =1 */
                   9356:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9357:              break;
                   9358:            case 2: /* ng=2 */
                   9359:              if(nagesqr==0)
                   9360:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9361:              else /* nagesqr =1 */
                   9362:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9363:              break;
                   9364:            case 3:
                   9365:              if(nagesqr==0)
                   9366:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9367:              else /* nagesqr =1 */
                   9368:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9369:              break;
                   9370:            }
                   9371:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9372:            ijp=1; /* product no age */
                   9373:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9374:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9375:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9376:              switch(Typevar[j]){
                   9377:              case 1:
                   9378:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9379:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9380:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9381:                      if(DummyV[j]==0){/* Bug valgrind */
                   9382:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9383:                      }else{ /* quantitative */
                   9384:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9385:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9386:                      }
                   9387:                      ij++;
1.268     brouard  9388:                    }
1.237     brouard  9389:                  }
1.329     brouard  9390:                }
                   9391:                break;
                   9392:              case 2:
                   9393:                if(cptcovprod >0){
                   9394:                  if(j==Tprod[ijp]) { /* */ 
                   9395:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9396:                    if(ijp <=cptcovprod) { /* Product */
                   9397:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9398:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9399:                          /* 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)]); */
                   9400:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9401:                        }else{ /* Vn is dummy and Vm is quanti */
                   9402:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9403:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9404:                        }
                   9405:                      }else{ /* Vn*Vm Vn is quanti */
                   9406:                        if(DummyV[Tvard[ijp][2]]==0){
                   9407:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9408:                        }else{ /* Both quanti */
                   9409:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9410:                        }
1.268     brouard  9411:                      }
1.329     brouard  9412:                      ijp++;
1.237     brouard  9413:                    }
1.329     brouard  9414:                  } /* end Tprod */
                   9415:                }
                   9416:                break;
1.349   ! brouard  9417:              case 3:
        !          9418:                if(cptcovdageprod >0){
        !          9419:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
        !          9420:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
        !          9421:                    if(ijp <=cptcovprod) { /* Product */
        !          9422:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
        !          9423:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
        !          9424:                          /* 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)]); */
        !          9425:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
        !          9426:                        }else{ /* Vn is dummy and Vm is quanti */
        !          9427:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
        !          9428:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
        !          9429:                        }
        !          9430:                      }else{ /* Vn*Vm Vn is quanti */
        !          9431:                        if(DummyV[Tvard[ijp][2]]==0){
        !          9432:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
        !          9433:                        }else{ /* Both quanti */
        !          9434:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
        !          9435:                        }
        !          9436:                      }
        !          9437:                      ijp++;
        !          9438:                    }
        !          9439:                    /* } */ /* end Tprod */
        !          9440:                }
        !          9441:                break;
1.329     brouard  9442:              case 0:
                   9443:                /* simple covariate */
1.264     brouard  9444:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9445:                if(Dummy[j]==0){
                   9446:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9447:                }else{ /* quantitative */
                   9448:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9449:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9450:                }
1.329     brouard  9451:               /* end simple */
                   9452:                break;
                   9453:              default:
                   9454:                break;
                   9455:              } /* end switch */
1.237     brouard  9456:            } /* end j */
1.329     brouard  9457:          }else{ /* k=k2 */
                   9458:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9459:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9460:            }else
                   9461:              i=i-ncovmodel;
1.223     brouard  9462:          }
1.227     brouard  9463:          
1.223     brouard  9464:          if(ng != 1){
                   9465:            fprintf(ficgp,")/(1");
1.227     brouard  9466:            
1.264     brouard  9467:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9468:              if(nagesqr==0)
1.264     brouard  9469:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9470:              else /* nagesqr =1 */
1.264     brouard  9471:                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  9472:               
1.223     brouard  9473:              ij=1;
1.329     brouard  9474:              ijp=1;
                   9475:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9476:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9477:                switch(Typevar[j]){
                   9478:                case 1:
                   9479:                  if(cptcovage >0){ 
                   9480:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9481:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9482:                        if(DummyV[j]==0){/* Bug valgrind */
                   9483:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9484:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9485:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9486:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9487:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9488:                        }else{ /* quantitative */
                   9489:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9490:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9491:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9492:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9493:                        }
                   9494:                        ij++;
                   9495:                      }
                   9496:                    }
                   9497:                  }
                   9498:                  break;
                   9499:                case 2:
                   9500:                  if(cptcovprod >0){
                   9501:                    if(j==Tprod[ijp]) { /* */ 
                   9502:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9503:                      if(ijp <=cptcovprod) { /* Product */
                   9504:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9505:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9506:                            /* 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)]); */
                   9507:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9508:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9509:                          }else{ /* Vn is dummy and Vm is quanti */
                   9510:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9511:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9512:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9513:                          }
                   9514:                        }else{ /* Vn*Vm Vn is quanti */
                   9515:                          if(DummyV[Tvard[ijp][2]]==0){
                   9516:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9517:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9518:                          }else{ /* Both quanti */
                   9519:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9520:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9521:                          } 
                   9522:                        }
                   9523:                        ijp++;
                   9524:                      }
                   9525:                    } /* end Tprod */
                   9526:                  } /* end if */
                   9527:                  break;
1.349   ! brouard  9528:                case 3:
        !          9529:                  if(cptcovdageprod >0){
        !          9530:                    /* if(j==Tprod[ijp]) { /\* *\/  */
        !          9531:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
        !          9532:                      if(ijp <=cptcovprod) { /* Product */
        !          9533:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
        !          9534:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
        !          9535:                            /* 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)]); */
        !          9536:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
        !          9537:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
        !          9538:                          }else{ /* Vn is dummy and Vm is quanti */
        !          9539:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
        !          9540:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
        !          9541:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
        !          9542:                          }
        !          9543:                        }else{ /* Vn*Vm Vn is quanti */
        !          9544:                          if(DummyV[Tvard[ijp][2]]==0){
        !          9545:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
        !          9546:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
        !          9547:                          }else{ /* Both quanti */
        !          9548:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
        !          9549:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
        !          9550:                          } 
        !          9551:                        }
        !          9552:                        ijp++;
        !          9553:                      }
        !          9554:                    /* } /\* end Tprod *\/ */
        !          9555:                  } /* end if */
        !          9556:                  break;
1.329     brouard  9557:                case 0: 
                   9558:                  /* simple covariate */
                   9559:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9560:                  if(Dummy[j]==0){
                   9561:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9562:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9563:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9564:                  }else{ /* quantitative */
                   9565:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9566:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9567:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9568:                  }
                   9569:                  /* end simple */
                   9570:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9571:                  break;
                   9572:                default:
                   9573:                  break;
                   9574:                } /* end switch */
1.223     brouard  9575:              }
                   9576:              fprintf(ficgp,")");
                   9577:            }
                   9578:            fprintf(ficgp,")");
                   9579:            if(ng ==2)
1.276     brouard  9580:              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  9581:            else /* ng= 3 */
1.276     brouard  9582:              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  9583:           }else{ /* end ng <> 1 */
1.223     brouard  9584:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9585:              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  9586:          }
                   9587:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9588:            fprintf(ficgp,",");
                   9589:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9590:            fprintf(ficgp,",");
                   9591:          i=i+ncovmodel;
                   9592:        } /* end k */
                   9593:       } /* end k2 */
1.276     brouard  9594:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9595:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9596:     } /* end resultline */
1.223     brouard  9597:   } /* end ng */
                   9598:   /* avoid: */
                   9599:   fflush(ficgp); 
1.126     brouard  9600: }  /* end gnuplot */
                   9601: 
                   9602: 
                   9603: /*************** Moving average **************/
1.219     brouard  9604: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9605:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9606:    
1.222     brouard  9607:    int i, cpt, cptcod;
                   9608:    int modcovmax =1;
                   9609:    int mobilavrange, mob;
                   9610:    int iage=0;
1.288     brouard  9611:    int firstA1=0, firstA2=0;
1.222     brouard  9612: 
1.266     brouard  9613:    double sum=0., sumr=0.;
1.222     brouard  9614:    double age;
1.266     brouard  9615:    double *sumnewp, *sumnewm, *sumnewmr;
                   9616:    double *agemingood, *agemaxgood; 
                   9617:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9618:   
                   9619:   
1.278     brouard  9620:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9621:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9622: 
                   9623:    sumnewp = vector(1,ncovcombmax);
                   9624:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9625:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9626:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9627:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9628:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9629:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9630: 
                   9631:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9632:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9633:      sumnewp[cptcod]=0.;
1.266     brouard  9634:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9635:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9636:    }
                   9637:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9638:   
1.266     brouard  9639:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9640:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9641:      else mobilavrange=mobilav;
                   9642:      for (age=bage; age<=fage; age++)
                   9643:        for (i=1; i<=nlstate;i++)
                   9644:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9645:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9646:      /* We keep the original values on the extreme ages bage, fage and for 
                   9647:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9648:        we use a 5 terms etc. until the borders are no more concerned. 
                   9649:      */ 
                   9650:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9651:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9652:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9653:           sumnewm[cptcod]=0.;
                   9654:           for (i=1; i<=nlstate;i++){
1.222     brouard  9655:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9656:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9657:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9658:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9659:             }
                   9660:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9661:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9662:           } /* end i */
                   9663:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9664:         } /* end cptcod */
1.222     brouard  9665:        }/* end age */
                   9666:      }/* end mob */
1.266     brouard  9667:    }else{
                   9668:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9669:      return -1;
1.266     brouard  9670:    }
                   9671: 
                   9672:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9673:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9674:      if(invalidvarcomb[cptcod]){
                   9675:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9676:        continue;
                   9677:      }
1.219     brouard  9678: 
1.266     brouard  9679:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9680:        sumnewm[cptcod]=0.;
                   9681:        sumnewmr[cptcod]=0.;
                   9682:        for (i=1; i<=nlstate;i++){
                   9683:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9684:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9685:        }
                   9686:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9687:         agemingoodr[cptcod]=age;
                   9688:        }
                   9689:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9690:           agemingood[cptcod]=age;
                   9691:        }
                   9692:      } /* age */
                   9693:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9694:        sumnewm[cptcod]=0.;
1.266     brouard  9695:        sumnewmr[cptcod]=0.;
1.222     brouard  9696:        for (i=1; i<=nlstate;i++){
                   9697:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9698:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9699:        }
                   9700:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9701:         agemaxgoodr[cptcod]=age;
1.222     brouard  9702:        }
                   9703:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9704:         agemaxgood[cptcod]=age;
                   9705:        }
                   9706:      } /* age */
                   9707:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9708:      /* but they will change */
1.288     brouard  9709:      firstA1=0;firstA2=0;
1.266     brouard  9710:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9711:        sumnewm[cptcod]=0.;
                   9712:        sumnewmr[cptcod]=0.;
                   9713:        for (i=1; i<=nlstate;i++){
                   9714:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9715:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9716:        }
                   9717:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9718:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9719:           agemaxgoodr[cptcod]=age;  /* age min */
                   9720:           for (i=1; i<=nlstate;i++)
                   9721:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9722:         }else{ /* bad we change the value with the values of good ages */
                   9723:           for (i=1; i<=nlstate;i++){
                   9724:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9725:           } /* i */
                   9726:         } /* end bad */
                   9727:        }else{
                   9728:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9729:           agemaxgood[cptcod]=age;
                   9730:         }else{ /* bad we change the value with the values of good ages */
                   9731:           for (i=1; i<=nlstate;i++){
                   9732:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9733:           } /* i */
                   9734:         } /* end bad */
                   9735:        }/* end else */
                   9736:        sum=0.;sumr=0.;
                   9737:        for (i=1; i<=nlstate;i++){
                   9738:         sum+=mobaverage[(int)age][i][cptcod];
                   9739:         sumr+=probs[(int)age][i][cptcod];
                   9740:        }
                   9741:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9742:         if(!firstA1){
                   9743:           firstA1=1;
                   9744:           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);
                   9745:         }
                   9746:         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  9747:        } /* end bad */
                   9748:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9749:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9750:         if(!firstA2){
                   9751:           firstA2=1;
                   9752:           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);
                   9753:         }
                   9754:         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  9755:        } /* end bad */
                   9756:      }/* age */
1.266     brouard  9757: 
                   9758:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9759:        sumnewm[cptcod]=0.;
1.266     brouard  9760:        sumnewmr[cptcod]=0.;
1.222     brouard  9761:        for (i=1; i<=nlstate;i++){
                   9762:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9763:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9764:        } 
                   9765:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9766:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9767:           agemingoodr[cptcod]=age;
                   9768:           for (i=1; i<=nlstate;i++)
                   9769:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9770:         }else{ /* bad we change the value with the values of good ages */
                   9771:           for (i=1; i<=nlstate;i++){
                   9772:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9773:           } /* i */
                   9774:         } /* end bad */
                   9775:        }else{
                   9776:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9777:           agemingood[cptcod]=age;
                   9778:         }else{ /* bad */
                   9779:           for (i=1; i<=nlstate;i++){
                   9780:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9781:           } /* i */
                   9782:         } /* end bad */
                   9783:        }/* end else */
                   9784:        sum=0.;sumr=0.;
                   9785:        for (i=1; i<=nlstate;i++){
                   9786:         sum+=mobaverage[(int)age][i][cptcod];
                   9787:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9788:        }
1.266     brouard  9789:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9790:         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  9791:        } /* end bad */
                   9792:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9793:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9794:         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  9795:        } /* end bad */
                   9796:      }/* age */
1.266     brouard  9797: 
1.222     brouard  9798:                
                   9799:      for (age=bage; age<=fage; age++){
1.235     brouard  9800:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9801:        sumnewp[cptcod]=0.;
                   9802:        sumnewm[cptcod]=0.;
                   9803:        for (i=1; i<=nlstate;i++){
                   9804:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9805:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9806:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9807:        }
                   9808:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9809:      }
                   9810:      /* printf("\n"); */
                   9811:      /* } */
1.266     brouard  9812: 
1.222     brouard  9813:      /* brutal averaging */
1.266     brouard  9814:      /* for (i=1; i<=nlstate;i++){ */
                   9815:      /*   for (age=1; age<=bage; age++){ */
                   9816:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9817:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9818:      /*   }     */
                   9819:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9820:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9821:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9822:      /*   } */
                   9823:      /* } /\* end i status *\/ */
                   9824:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9825:      /*   for (age=1; age<=AGESUP; age++){ */
                   9826:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9827:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9828:      /*   } */
                   9829:      /* } */
1.222     brouard  9830:    }/* end cptcod */
1.266     brouard  9831:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9832:    free_vector(agemaxgood,1, ncovcombmax);
                   9833:    free_vector(agemingood,1, ncovcombmax);
                   9834:    free_vector(agemingoodr,1, ncovcombmax);
                   9835:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9836:    free_vector(sumnewm,1, ncovcombmax);
                   9837:    free_vector(sumnewp,1, ncovcombmax);
                   9838:    return 0;
                   9839:  }/* End movingaverage */
1.218     brouard  9840:  
1.126     brouard  9841: 
1.296     brouard  9842:  
1.126     brouard  9843: /************** Forecasting ******************/
1.296     brouard  9844: /* 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)*/
                   9845: 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){
                   9846:   /* dateintemean, mean date of interviews
                   9847:      dateprojd, year, month, day of starting projection 
                   9848:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9849:      agemin, agemax range of age
                   9850:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9851:   */
1.296     brouard  9852:   /* double anprojd, mprojd, jprojd; */
                   9853:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9854:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9855:   double agec; /* generic age */
1.296     brouard  9856:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9857:   double *popeffectif,*popcount;
                   9858:   double ***p3mat;
1.218     brouard  9859:   /* double ***mobaverage; */
1.126     brouard  9860:   char fileresf[FILENAMELENGTH];
                   9861: 
                   9862:   agelim=AGESUP;
1.211     brouard  9863:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9864:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9865:      We still use firstpass and lastpass as another selection.
                   9866:   */
1.214     brouard  9867:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9868:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9869:  
1.201     brouard  9870:   strcpy(fileresf,"F_"); 
                   9871:   strcat(fileresf,fileresu);
1.126     brouard  9872:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9873:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9874:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9875:   }
1.235     brouard  9876:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9877:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9878: 
1.225     brouard  9879:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9880: 
                   9881: 
                   9882:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9883:   if (stepm<=12) stepsize=1;
                   9884:   if(estepm < stepm){
                   9885:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9886:   }
1.270     brouard  9887:   else{
                   9888:     hstepm=estepm;   
                   9889:   }
                   9890:   if(estepm > stepm){ /* Yes every two year */
                   9891:     stepsize=2;
                   9892:   }
1.296     brouard  9893:   hstepm=hstepm/stepm;
1.126     brouard  9894: 
1.296     brouard  9895:   
                   9896:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9897:   /*                              fractional in yp1 *\/ */
                   9898:   /* aintmean=yp; */
                   9899:   /* yp2=modf((yp1*12),&yp); */
                   9900:   /* mintmean=yp; */
                   9901:   /* yp1=modf((yp2*30.5),&yp); */
                   9902:   /* jintmean=yp; */
                   9903:   /* if(jintmean==0) jintmean=1; */
                   9904:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9905: 
1.296     brouard  9906: 
                   9907:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9908:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9909:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9910:   i1=pow(2,cptcoveff);
1.126     brouard  9911:   if (cptcovn < 1){i1=1;}
                   9912:   
1.296     brouard  9913:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9914:   
                   9915:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9916:   
1.126     brouard  9917: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9918:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9919:     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  9920:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9921:       continue;
1.227     brouard  9922:     if(invalidvarcomb[k]){
                   9923:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9924:       continue;
                   9925:     }
                   9926:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9927:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9928:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9929:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9930:     }
1.235     brouard  9931:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9932:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9933:     }
1.227     brouard  9934:     fprintf(ficresf," yearproj age");
                   9935:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9936:       for(i=1; i<=nlstate;i++)               
                   9937:        fprintf(ficresf," p%d%d",i,j);
                   9938:       fprintf(ficresf," wp.%d",j);
                   9939:     }
1.296     brouard  9940:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9941:       fprintf(ficresf,"\n");
1.296     brouard  9942:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9943:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9944:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9945:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9946:        nhstepm = nhstepm/hstepm; 
                   9947:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9948:        oldm=oldms;savm=savms;
1.268     brouard  9949:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9950:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9951:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9952:        for (h=0; h<=nhstepm; h++){
                   9953:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9954:            break;
                   9955:          }
                   9956:        }
                   9957:        fprintf(ficresf,"\n");
                   9958:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9959:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9960:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9961:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9962:        
                   9963:        for(j=1; j<=nlstate+ndeath;j++) {
                   9964:          ppij=0.;
                   9965:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9966:            if (mobilav>=1)
                   9967:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9968:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9969:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9970:            }
1.268     brouard  9971:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9972:          } /* end i */
                   9973:          fprintf(ficresf," %.3f", ppij);
                   9974:        }/* end j */
1.227     brouard  9975:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9976:       } /* end agec */
1.266     brouard  9977:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9978:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9979:     } /* end yearp */
                   9980:   } /* end  k */
1.219     brouard  9981:        
1.126     brouard  9982:   fclose(ficresf);
1.215     brouard  9983:   printf("End of Computing forecasting \n");
                   9984:   fprintf(ficlog,"End of Computing forecasting\n");
                   9985: 
1.126     brouard  9986: }
                   9987: 
1.269     brouard  9988: /************** Back Forecasting ******************/
1.296     brouard  9989:  /* 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){ */
                   9990:  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){
                   9991:   /* back1, year, month, day of starting backprojection
1.267     brouard  9992:      agemin, agemax range of age
                   9993:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9994:      anback2 year of end of backprojection (same day and month as back1).
                   9995:      prevacurrent and prev are prevalences.
1.267     brouard  9996:   */
                   9997:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9998:   double agec; /* generic age */
1.302     brouard  9999:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10000:   double *popeffectif,*popcount;
                   10001:   double ***p3mat;
                   10002:   /* double ***mobaverage; */
                   10003:   char fileresfb[FILENAMELENGTH];
                   10004:  
1.268     brouard  10005:   agelim=AGEINF;
1.267     brouard  10006:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10007:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10008:      We still use firstpass and lastpass as another selection.
                   10009:   */
                   10010:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10011:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10012: 
                   10013:   /*Do we need to compute prevalence again?*/
                   10014: 
                   10015:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10016:   
                   10017:   strcpy(fileresfb,"FB_");
                   10018:   strcat(fileresfb,fileresu);
                   10019:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10020:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10021:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10022:   }
                   10023:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10024:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10025:   
                   10026:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10027:   
                   10028:    
                   10029:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10030:   if (stepm<=12) stepsize=1;
                   10031:   if(estepm < stepm){
                   10032:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10033:   }
1.270     brouard  10034:   else{
                   10035:     hstepm=estepm;   
                   10036:   }
                   10037:   if(estepm >= stepm){ /* Yes every two year */
                   10038:     stepsize=2;
                   10039:   }
1.267     brouard  10040:   
                   10041:   hstepm=hstepm/stepm;
1.296     brouard  10042:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10043:   /*                              fractional in yp1 *\/ */
                   10044:   /* aintmean=yp; */
                   10045:   /* yp2=modf((yp1*12),&yp); */
                   10046:   /* mintmean=yp; */
                   10047:   /* yp1=modf((yp2*30.5),&yp); */
                   10048:   /* jintmean=yp; */
                   10049:   /* if(jintmean==0) jintmean=1; */
                   10050:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10051:   
                   10052:   i1=pow(2,cptcoveff);
                   10053:   if (cptcovn < 1){i1=1;}
                   10054:   
1.296     brouard  10055:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10056:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10057:   
                   10058:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10059:   
                   10060:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10061:   for(k=1; k<=i1;k++){
                   10062:     if(i1 != 1 && TKresult[nres]!= k)
                   10063:       continue;
                   10064:     if(invalidvarcomb[k]){
                   10065:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   10066:       continue;
                   10067:     }
1.268     brouard  10068:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  10069:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  10070:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  10071:     }
                   10072:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10073:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10074:     }
                   10075:     fprintf(ficresfb," yearbproj age");
                   10076:     for(j=1; j<=nlstate+ndeath;j++){
                   10077:       for(i=1; i<=nlstate;i++)
1.268     brouard  10078:        fprintf(ficresfb," b%d%d",i,j);
                   10079:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10080:     }
1.296     brouard  10081:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10082:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10083:       fprintf(ficresfb,"\n");
1.296     brouard  10084:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10085:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10086:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10087:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10088:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10089:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10090:        nhstepm = nhstepm/hstepm;
                   10091:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10092:        oldm=oldms;savm=savms;
1.268     brouard  10093:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10094:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10095:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10096:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10097:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10098:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10099:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10100:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10101:            break;
                   10102:          }
                   10103:        }
                   10104:        fprintf(ficresfb,"\n");
                   10105:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  10106:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  10107:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10108:        for(i=1; i<=nlstate+ndeath;i++) {
                   10109:          ppij=0.;ppi=0.;
                   10110:          for(j=1; j<=nlstate;j++) {
                   10111:            /* if (mobilav==1) */
1.269     brouard  10112:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10113:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10114:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10115:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10116:              /* else { */
                   10117:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10118:              /* } */
1.268     brouard  10119:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10120:          } /* end j */
                   10121:          if(ppi <0.99){
                   10122:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10123:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10124:          }
                   10125:          fprintf(ficresfb," %.3f", ppij);
                   10126:        }/* end j */
1.267     brouard  10127:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10128:       } /* end agec */
                   10129:     } /* end yearp */
                   10130:   } /* end k */
1.217     brouard  10131:   
1.267     brouard  10132:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10133:   
1.267     brouard  10134:   fclose(ficresfb);
                   10135:   printf("End of Computing Back forecasting \n");
                   10136:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10137:        
1.267     brouard  10138: }
1.217     brouard  10139: 
1.269     brouard  10140: /* Variance of prevalence limit: varprlim */
                   10141:  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  10142:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10143:  
                   10144:    char fileresvpl[FILENAMELENGTH];  
                   10145:    FILE *ficresvpl;
                   10146:    double **oldm, **savm;
                   10147:    double **varpl; /* Variances of prevalence limits by age */   
                   10148:    int i1, k, nres, j ;
                   10149:    
                   10150:     strcpy(fileresvpl,"VPL_");
                   10151:     strcat(fileresvpl,fileresu);
                   10152:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10153:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10154:       exit(0);
                   10155:     }
1.288     brouard  10156:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10157:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10158:     
                   10159:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10160:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10161:     
                   10162:     i1=pow(2,cptcoveff);
                   10163:     if (cptcovn < 1){i1=1;}
                   10164: 
1.337     brouard  10165:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10166:        k=TKresult[nres];
1.338     brouard  10167:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10168:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10169:       if(i1 != 1 && TKresult[nres]!= k)
                   10170:        continue;
                   10171:       fprintf(ficresvpl,"\n#****** ");
                   10172:       printf("\n#****** ");
                   10173:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10174:       for(j=1;j<=cptcovs;j++) {
                   10175:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10176:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10177:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10178:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10179:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10180:       }
1.337     brouard  10181:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10182:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10183:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10184:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10185:       /* }      */
1.269     brouard  10186:       fprintf(ficresvpl,"******\n");
                   10187:       printf("******\n");
                   10188:       fprintf(ficlog,"******\n");
                   10189:       
                   10190:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10191:       oldm=oldms;savm=savms;
                   10192:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10193:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10194:       /*}*/
                   10195:     }
                   10196:     
                   10197:     fclose(ficresvpl);
1.288     brouard  10198:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10199:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10200: 
                   10201:  }
                   10202: /* Variance of back prevalence: varbprlim */
                   10203:  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){
                   10204:       /*------- Variance of back (stable) prevalence------*/
                   10205: 
                   10206:    char fileresvbl[FILENAMELENGTH];  
                   10207:    FILE  *ficresvbl;
                   10208: 
                   10209:    double **oldm, **savm;
                   10210:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10211:    int i1, k, nres, j ;
                   10212: 
                   10213:    strcpy(fileresvbl,"VBL_");
                   10214:    strcat(fileresvbl,fileresu);
                   10215:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10216:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10217:      exit(0);
                   10218:    }
                   10219:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10220:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10221:    
                   10222:    
                   10223:    i1=pow(2,cptcoveff);
                   10224:    if (cptcovn < 1){i1=1;}
                   10225:    
1.337     brouard  10226:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10227:      k=TKresult[nres];
1.338     brouard  10228:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10229:     /* for(k=1; k<=i1;k++){ */
                   10230:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10231:     /*          continue; */
1.269     brouard  10232:        fprintf(ficresvbl,"\n#****** ");
                   10233:        printf("\n#****** ");
                   10234:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10235:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10236:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10237:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10238:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10239:        /* for(j=1;j<=cptcoveff;j++) { */
                   10240:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10241:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10242:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10243:        /* } */
                   10244:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10245:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10246:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10247:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10248:        }
                   10249:        fprintf(ficresvbl,"******\n");
                   10250:        printf("******\n");
                   10251:        fprintf(ficlog,"******\n");
                   10252:        
                   10253:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10254:        oldm=oldms;savm=savms;
                   10255:        
                   10256:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10257:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10258:        /*}*/
                   10259:      }
                   10260:    
                   10261:    fclose(ficresvbl);
                   10262:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10263:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10264: 
                   10265:  } /* End of varbprlim */
                   10266: 
1.126     brouard  10267: /************** Forecasting *****not tested NB*************/
1.227     brouard  10268: /* 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  10269:   
1.227     brouard  10270: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10271: /*   int *popage; */
                   10272: /*   double calagedatem, agelim, kk1, kk2; */
                   10273: /*   double *popeffectif,*popcount; */
                   10274: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10275: /*   /\* double ***mobaverage; *\/ */
                   10276: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10277: 
1.227     brouard  10278: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10279: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10280: /*   agelim=AGESUP; */
                   10281: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10282:   
1.227     brouard  10283: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10284:   
                   10285:   
1.227     brouard  10286: /*   strcpy(filerespop,"POP_");  */
                   10287: /*   strcat(filerespop,fileresu); */
                   10288: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10289: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10290: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10291: /*   } */
                   10292: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10293: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10294: 
1.227     brouard  10295: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10296: 
1.227     brouard  10297: /*   /\* if (mobilav!=0) { *\/ */
                   10298: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10299: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10300: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10301: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10302: /*   /\*   } *\/ */
                   10303: /*   /\* } *\/ */
1.126     brouard  10304: 
1.227     brouard  10305: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10306: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10307:   
1.227     brouard  10308: /*   agelim=AGESUP; */
1.126     brouard  10309:   
1.227     brouard  10310: /*   hstepm=1; */
                   10311: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10312:        
1.227     brouard  10313: /*   if (popforecast==1) { */
                   10314: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10315: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10316: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10317: /*     }  */
                   10318: /*     popage=ivector(0,AGESUP); */
                   10319: /*     popeffectif=vector(0,AGESUP); */
                   10320: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10321:     
1.227     brouard  10322: /*     i=1;    */
                   10323: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10324:     
1.227     brouard  10325: /*     imx=i; */
                   10326: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10327: /*   } */
1.218     brouard  10328:   
1.227     brouard  10329: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10330: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10331: /*       k=k+1; */
                   10332: /*       fprintf(ficrespop,"\n#******"); */
                   10333: /*       for(j=1;j<=cptcoveff;j++) { */
                   10334: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10335: /*       } */
                   10336: /*       fprintf(ficrespop,"******\n"); */
                   10337: /*       fprintf(ficrespop,"# Age"); */
                   10338: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10339: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10340:       
1.227     brouard  10341: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10342: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10343:        
1.227     brouard  10344: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10345: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10346: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10347:          
1.227     brouard  10348: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10349: /*       oldm=oldms;savm=savms; */
                   10350: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10351:          
1.227     brouard  10352: /*       for (h=0; h<=nhstepm; h++){ */
                   10353: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10354: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10355: /*         }  */
                   10356: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10357: /*           kk1=0.;kk2=0; */
                   10358: /*           for(i=1; i<=nlstate;i++) {               */
                   10359: /*             if (mobilav==1)  */
                   10360: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10361: /*             else { */
                   10362: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10363: /*             } */
                   10364: /*           } */
                   10365: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10366: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10367: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10368: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10369: /*           } */
                   10370: /*         } */
                   10371: /*         for(i=1; i<=nlstate;i++){ */
                   10372: /*           kk1=0.; */
                   10373: /*           for(j=1; j<=nlstate;j++){ */
                   10374: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10375: /*           } */
                   10376: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10377: /*         } */
1.218     brouard  10378:            
1.227     brouard  10379: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10380: /*           for(j=1; j<=nlstate;j++)  */
                   10381: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10382: /*       } */
                   10383: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10384: /*     } */
                   10385: /*       } */
1.218     brouard  10386:       
1.227     brouard  10387: /*       /\******\/ */
1.218     brouard  10388:       
1.227     brouard  10389: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10390: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10391: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10392: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10393: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10394:          
1.227     brouard  10395: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10396: /*       oldm=oldms;savm=savms; */
                   10397: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10398: /*       for (h=0; h<=nhstepm; h++){ */
                   10399: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10400: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10401: /*         }  */
                   10402: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10403: /*           kk1=0.;kk2=0; */
                   10404: /*           for(i=1; i<=nlstate;i++) {               */
                   10405: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10406: /*           } */
                   10407: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10408: /*         } */
                   10409: /*       } */
                   10410: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10411: /*     } */
                   10412: /*       } */
                   10413: /*     }  */
                   10414: /*   } */
1.218     brouard  10415:   
1.227     brouard  10416: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10417:   
1.227     brouard  10418: /*   if (popforecast==1) { */
                   10419: /*     free_ivector(popage,0,AGESUP); */
                   10420: /*     free_vector(popeffectif,0,AGESUP); */
                   10421: /*     free_vector(popcount,0,AGESUP); */
                   10422: /*   } */
                   10423: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10424: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10425: /*   fclose(ficrespop); */
                   10426: /* } /\* End of popforecast *\/ */
1.218     brouard  10427:  
1.126     brouard  10428: int fileappend(FILE *fichier, char *optionfich)
                   10429: {
                   10430:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10431:     printf("Problem with file: %s\n", optionfich);
                   10432:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10433:     return (0);
                   10434:   }
                   10435:   fflush(fichier);
                   10436:   return (1);
                   10437: }
                   10438: 
                   10439: 
                   10440: /**************** function prwizard **********************/
                   10441: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10442: {
                   10443: 
                   10444:   /* Wizard to print covariance matrix template */
                   10445: 
1.164     brouard  10446:   char ca[32], cb[32];
                   10447:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10448:   int numlinepar;
                   10449: 
                   10450:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10451:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10452:   for(i=1; i <=nlstate; i++){
                   10453:     jj=0;
                   10454:     for(j=1; j <=nlstate+ndeath; j++){
                   10455:       if(j==i) continue;
                   10456:       jj++;
                   10457:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10458:       printf("%1d%1d",i,j);
                   10459:       fprintf(ficparo,"%1d%1d",i,j);
                   10460:       for(k=1; k<=ncovmodel;k++){
                   10461:        /*        printf(" %lf",param[i][j][k]); */
                   10462:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10463:        printf(" 0.");
                   10464:        fprintf(ficparo," 0.");
                   10465:       }
                   10466:       printf("\n");
                   10467:       fprintf(ficparo,"\n");
                   10468:     }
                   10469:   }
                   10470:   printf("# Scales (for hessian or gradient estimation)\n");
                   10471:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10472:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10473:   for(i=1; i <=nlstate; i++){
                   10474:     jj=0;
                   10475:     for(j=1; j <=nlstate+ndeath; j++){
                   10476:       if(j==i) continue;
                   10477:       jj++;
                   10478:       fprintf(ficparo,"%1d%1d",i,j);
                   10479:       printf("%1d%1d",i,j);
                   10480:       fflush(stdout);
                   10481:       for(k=1; k<=ncovmodel;k++){
                   10482:        /*      printf(" %le",delti3[i][j][k]); */
                   10483:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10484:        printf(" 0.");
                   10485:        fprintf(ficparo," 0.");
                   10486:       }
                   10487:       numlinepar++;
                   10488:       printf("\n");
                   10489:       fprintf(ficparo,"\n");
                   10490:     }
                   10491:   }
                   10492:   printf("# Covariance matrix\n");
                   10493: /* # 121 Var(a12)\n\ */
                   10494: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10495: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10496: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10497: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10498: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10499: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10500: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10501:   fflush(stdout);
                   10502:   fprintf(ficparo,"# Covariance matrix\n");
                   10503:   /* # 121 Var(a12)\n\ */
                   10504:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10505:   /* #   ...\n\ */
                   10506:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10507:   
                   10508:   for(itimes=1;itimes<=2;itimes++){
                   10509:     jj=0;
                   10510:     for(i=1; i <=nlstate; i++){
                   10511:       for(j=1; j <=nlstate+ndeath; j++){
                   10512:        if(j==i) continue;
                   10513:        for(k=1; k<=ncovmodel;k++){
                   10514:          jj++;
                   10515:          ca[0]= k+'a'-1;ca[1]='\0';
                   10516:          if(itimes==1){
                   10517:            printf("#%1d%1d%d",i,j,k);
                   10518:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10519:          }else{
                   10520:            printf("%1d%1d%d",i,j,k);
                   10521:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10522:            /*  printf(" %.5le",matcov[i][j]); */
                   10523:          }
                   10524:          ll=0;
                   10525:          for(li=1;li <=nlstate; li++){
                   10526:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10527:              if(lj==li) continue;
                   10528:              for(lk=1;lk<=ncovmodel;lk++){
                   10529:                ll++;
                   10530:                if(ll<=jj){
                   10531:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10532:                  if(ll<jj){
                   10533:                    if(itimes==1){
                   10534:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10535:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10536:                    }else{
                   10537:                      printf(" 0.");
                   10538:                      fprintf(ficparo," 0.");
                   10539:                    }
                   10540:                  }else{
                   10541:                    if(itimes==1){
                   10542:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10543:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10544:                    }else{
                   10545:                      printf(" 0.");
                   10546:                      fprintf(ficparo," 0.");
                   10547:                    }
                   10548:                  }
                   10549:                }
                   10550:              } /* end lk */
                   10551:            } /* end lj */
                   10552:          } /* end li */
                   10553:          printf("\n");
                   10554:          fprintf(ficparo,"\n");
                   10555:          numlinepar++;
                   10556:        } /* end k*/
                   10557:       } /*end j */
                   10558:     } /* end i */
                   10559:   } /* end itimes */
                   10560: 
                   10561: } /* end of prwizard */
                   10562: /******************* Gompertz Likelihood ******************************/
                   10563: double gompertz(double x[])
                   10564: { 
1.302     brouard  10565:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10566:   int i,n=0; /* n is the size of the sample */
                   10567: 
1.220     brouard  10568:   for (i=1;i<=imx ; i++) {
1.126     brouard  10569:     sump=sump+weight[i];
                   10570:     /*    sump=sump+1;*/
                   10571:     num=num+1;
                   10572:   }
1.302     brouard  10573:   L=0.0;
                   10574:   /* agegomp=AGEGOMP; */
1.126     brouard  10575:   /* for (i=0; i<=imx; i++) 
                   10576:      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]);*/
                   10577: 
1.302     brouard  10578:   for (i=1;i<=imx ; i++) {
                   10579:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10580:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10581:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10582:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10583:      * +
                   10584:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10585:      */
                   10586:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10587:        if (cens[i] == 1){
                   10588:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10589:        } else if (cens[i] == 0){
1.126     brouard  10590:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10591:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10592:       } else
                   10593:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10594:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10595:        L=L+A*weight[i];
1.126     brouard  10596:        /*      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  10597:      }
                   10598:   }
1.126     brouard  10599: 
1.302     brouard  10600:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10601:  
                   10602:   return -2*L*num/sump;
                   10603: }
                   10604: 
1.136     brouard  10605: #ifdef GSL
                   10606: /******************* Gompertz_f Likelihood ******************************/
                   10607: double gompertz_f(const gsl_vector *v, void *params)
                   10608: { 
1.302     brouard  10609:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10610:   double *x= (double *) v->data;
                   10611:   int i,n=0; /* n is the size of the sample */
                   10612: 
                   10613:   for (i=0;i<=imx-1 ; i++) {
                   10614:     sump=sump+weight[i];
                   10615:     /*    sump=sump+1;*/
                   10616:     num=num+1;
                   10617:   }
                   10618:  
                   10619:  
                   10620:   /* for (i=0; i<=imx; i++) 
                   10621:      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]);*/
                   10622:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10623:   for (i=1;i<=imx ; i++)
                   10624:     {
                   10625:       if (cens[i] == 1 && wav[i]>1)
                   10626:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10627:       
                   10628:       if (cens[i] == 0 && wav[i]>1)
                   10629:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10630:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10631:       
                   10632:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10633:       if (wav[i] > 1 ) { /* ??? */
                   10634:        LL=LL+A*weight[i];
                   10635:        /*      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]);*/
                   10636:       }
                   10637:     }
                   10638: 
                   10639:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10640:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10641:  
                   10642:   return -2*LL*num/sump;
                   10643: }
                   10644: #endif
                   10645: 
1.126     brouard  10646: /******************* Printing html file ***********/
1.201     brouard  10647: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10648:                  int lastpass, int stepm, int weightopt, char model[],\
                   10649:                  int imx,  double p[],double **matcov,double agemortsup){
                   10650:   int i,k;
                   10651: 
                   10652:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10653:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10654:   for (i=1;i<=2;i++) 
                   10655:     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  10656:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10657:   fprintf(fichtm,"</ul>");
                   10658: 
                   10659: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10660: 
                   10661:  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>");
                   10662: 
                   10663:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10664:    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]);
                   10665: 
                   10666:  
                   10667:   fflush(fichtm);
                   10668: }
                   10669: 
                   10670: /******************* Gnuplot file **************/
1.201     brouard  10671: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10672: 
                   10673:   char dirfileres[132],optfileres[132];
1.164     brouard  10674: 
1.126     brouard  10675:   int ng;
                   10676: 
                   10677: 
                   10678:   /*#ifdef windows */
                   10679:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10680:     /*#endif */
                   10681: 
                   10682: 
                   10683:   strcpy(dirfileres,optionfilefiname);
                   10684:   strcpy(optfileres,"vpl");
1.199     brouard  10685:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10686:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10687:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10688:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10689:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10690: 
                   10691: } 
                   10692: 
1.136     brouard  10693: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10694: {
1.126     brouard  10695: 
1.136     brouard  10696:   /*-------- data file ----------*/
                   10697:   FILE *fic;
                   10698:   char dummy[]="                         ";
1.240     brouard  10699:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10700:   int lstra;
1.136     brouard  10701:   int linei, month, year,iout;
1.302     brouard  10702:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10703:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10704:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10705:   char *stratrunc;
1.223     brouard  10706: 
1.349   ! brouard  10707:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
        !          10708:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10709:   
                   10710:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10711:   
1.136     brouard  10712:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10713:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10714:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10715:   }
1.126     brouard  10716: 
1.302     brouard  10717:     /* Is it a BOM UTF-8 Windows file? */
                   10718:   /* First data line */
                   10719:   linei=0;
                   10720:   while(fgets(line, MAXLINE, fic)) {
                   10721:     noffset=0;
                   10722:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10723:     {
                   10724:       noffset=noffset+3;
                   10725:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10726:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10727:       fflush(ficlog); return 1;
                   10728:     }
                   10729:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10730:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10731:     {
                   10732:       noffset=noffset+2;
1.304     brouard  10733:       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);
                   10734:       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  10735:       fflush(ficlog); return 1;
                   10736:     }
                   10737:     else if( line[0] == 0 && line[1] == 0)
                   10738:     {
                   10739:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10740:        noffset=noffset+4;
1.304     brouard  10741:        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);
                   10742:        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  10743:        fflush(ficlog); return 1;
                   10744:       }
                   10745:     } else{
                   10746:       ;/*printf(" Not a BOM file\n");*/
                   10747:     }
                   10748:         /* If line starts with a # it is a comment */
                   10749:     if (line[noffset] == '#') {
                   10750:       linei=linei+1;
                   10751:       break;
                   10752:     }else{
                   10753:       break;
                   10754:     }
                   10755:   }
                   10756:   fclose(fic);
                   10757:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10758:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10759:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10760:   }
                   10761:   /* Not a Bom file */
                   10762:   
1.136     brouard  10763:   i=1;
                   10764:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10765:     linei=linei+1;
                   10766:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10767:       if(line[j] == '\t')
                   10768:        line[j] = ' ';
                   10769:     }
                   10770:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10771:       ;
                   10772:     };
                   10773:     line[j+1]=0;  /* Trims blanks at end of line */
                   10774:     if(line[0]=='#'){
                   10775:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10776:       printf("Comment line\n%s\n",line);
                   10777:       continue;
                   10778:     }
                   10779:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10780:     strcpy(line, linetmp);
1.223     brouard  10781:     
                   10782:     /* Loops on waves */
                   10783:     for (j=maxwav;j>=1;j--){
                   10784:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10785:        cutv(stra, strb, line, ' '); 
                   10786:        if(strb[0]=='.') { /* Missing value */
                   10787:          lval=-1;
                   10788:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10789:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10790:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10791:            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);
                   10792:            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);
                   10793:            return 1;
                   10794:          }
                   10795:        }else{
                   10796:          errno=0;
                   10797:          /* what_kind_of_number(strb); */
                   10798:          dval=strtod(strb,&endptr); 
                   10799:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10800:          /* if(strb != endptr && *endptr == '\0') */
                   10801:          /*    dval=dlval; */
                   10802:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10803:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10804:            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);
                   10805:            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);
                   10806:            return 1;
                   10807:          }
                   10808:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10809:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10810:        }
                   10811:        strcpy(line,stra);
1.223     brouard  10812:       }/* end loop ntqv */
1.225     brouard  10813:       
1.223     brouard  10814:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10815:        cutv(stra, strb, line, ' '); 
                   10816:        if(strb[0]=='.') { /* Missing value */
                   10817:          lval=-1;
                   10818:        }else{
                   10819:          errno=0;
                   10820:          lval=strtol(strb,&endptr,10); 
                   10821:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10822:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10823:            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);
                   10824:            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);
                   10825:            return 1;
                   10826:          }
                   10827:        }
                   10828:        if(lval <-1 || lval >1){
                   10829:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10830:  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  10831:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10832:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10833:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10834:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10835:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10836:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10837:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10838:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10839:  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  10840:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10841:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10842:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10843:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10844:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10845:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10846:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10847:          return 1;
                   10848:        }
1.341     brouard  10849:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10850:        strcpy(line,stra);
1.223     brouard  10851:       }/* end loop ntv */
1.225     brouard  10852:       
1.223     brouard  10853:       /* Statuses  at wave */
1.137     brouard  10854:       cutv(stra, strb, line, ' '); 
1.223     brouard  10855:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10856:        lval=-1;
1.136     brouard  10857:       }else{
1.238     brouard  10858:        errno=0;
                   10859:        lval=strtol(strb,&endptr,10); 
                   10860:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10861:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10862:          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);
                   10863:          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);
                   10864:          return 1;
                   10865:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10866:          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);
                   10867:          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  10868:          return 1;
                   10869:        }
1.136     brouard  10870:       }
1.225     brouard  10871:       
1.136     brouard  10872:       s[j][i]=lval;
1.225     brouard  10873:       
1.223     brouard  10874:       /* Date of Interview */
1.136     brouard  10875:       strcpy(line,stra);
                   10876:       cutv(stra, strb,line,' ');
1.169     brouard  10877:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10878:       }
1.169     brouard  10879:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10880:        month=99;
                   10881:        year=9999;
1.136     brouard  10882:       }else{
1.225     brouard  10883:        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);
                   10884:        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);
                   10885:        return 1;
1.136     brouard  10886:       }
                   10887:       anint[j][i]= (double) year; 
1.302     brouard  10888:       mint[j][i]= (double)month;
                   10889:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10890:       /*       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]); */
                   10891:       /*       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]); */
                   10892:       /* } */
1.136     brouard  10893:       strcpy(line,stra);
1.223     brouard  10894:     } /* End loop on waves */
1.225     brouard  10895:     
1.223     brouard  10896:     /* Date of death */
1.136     brouard  10897:     cutv(stra, strb,line,' '); 
1.169     brouard  10898:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10899:     }
1.169     brouard  10900:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10901:       month=99;
                   10902:       year=9999;
                   10903:     }else{
1.141     brouard  10904:       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  10905:       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);
                   10906:       return 1;
1.136     brouard  10907:     }
                   10908:     andc[i]=(double) year; 
                   10909:     moisdc[i]=(double) month; 
                   10910:     strcpy(line,stra);
                   10911:     
1.223     brouard  10912:     /* Date of birth */
1.136     brouard  10913:     cutv(stra, strb,line,' '); 
1.169     brouard  10914:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10915:     }
1.169     brouard  10916:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10917:       month=99;
                   10918:       year=9999;
                   10919:     }else{
1.141     brouard  10920:       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);
                   10921:       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  10922:       return 1;
1.136     brouard  10923:     }
                   10924:     if (year==9999) {
1.141     brouard  10925:       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);
                   10926:       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  10927:       return 1;
                   10928:       
1.136     brouard  10929:     }
                   10930:     annais[i]=(double)(year);
1.302     brouard  10931:     moisnais[i]=(double)(month);
                   10932:     for (j=1;j<=maxwav;j++){
                   10933:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10934:        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]);
                   10935:        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]);
                   10936:       }
                   10937:     }
                   10938: 
1.136     brouard  10939:     strcpy(line,stra);
1.225     brouard  10940:     
1.223     brouard  10941:     /* Sample weight */
1.136     brouard  10942:     cutv(stra, strb,line,' '); 
                   10943:     errno=0;
                   10944:     dval=strtod(strb,&endptr); 
                   10945:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10946:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10947:       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  10948:       fflush(ficlog);
                   10949:       return 1;
                   10950:     }
                   10951:     weight[i]=dval; 
                   10952:     strcpy(line,stra);
1.225     brouard  10953:     
1.223     brouard  10954:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10955:       cutv(stra, strb, line, ' '); 
                   10956:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10957:        lval=-1;
1.311     brouard  10958:        coqvar[iv][i]=NAN; 
                   10959:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10960:       }else{
1.225     brouard  10961:        errno=0;
                   10962:        /* what_kind_of_number(strb); */
                   10963:        dval=strtod(strb,&endptr);
                   10964:        /* if(strb != endptr && *endptr == '\0') */
                   10965:        /*   dval=dlval; */
                   10966:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10967:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10968:          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);
                   10969:          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);
                   10970:          return 1;
                   10971:        }
                   10972:        coqvar[iv][i]=dval; 
1.226     brouard  10973:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10974:       }
                   10975:       strcpy(line,stra);
                   10976:     }/* end loop nqv */
1.136     brouard  10977:     
1.223     brouard  10978:     /* Covariate values */
1.136     brouard  10979:     for (j=ncovcol;j>=1;j--){
                   10980:       cutv(stra, strb,line,' '); 
1.223     brouard  10981:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10982:        lval=-1;
1.136     brouard  10983:       }else{
1.225     brouard  10984:        errno=0;
                   10985:        lval=strtol(strb,&endptr,10); 
                   10986:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10987:          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);
                   10988:          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);
                   10989:          return 1;
                   10990:        }
1.136     brouard  10991:       }
                   10992:       if(lval <-1 || lval >1){
1.225     brouard  10993:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10994:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10995:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10996:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10997:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10998:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10999:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11000:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11001:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11002:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11003:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11004:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11005:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11006:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11007:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11008:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11009:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11010:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11011:        return 1;
1.136     brouard  11012:       }
                   11013:       covar[j][i]=(double)(lval);
                   11014:       strcpy(line,stra);
                   11015:     }  
                   11016:     lstra=strlen(stra);
1.225     brouard  11017:     
1.136     brouard  11018:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11019:       stratrunc = &(stra[lstra-9]);
                   11020:       num[i]=atol(stratrunc);
                   11021:     }
                   11022:     else
                   11023:       num[i]=atol(stra);
                   11024:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11025:       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;}*/
                   11026:     
                   11027:     i=i+1;
                   11028:   } /* End loop reading  data */
1.225     brouard  11029:   
1.136     brouard  11030:   *imax=i-1; /* Number of individuals */
                   11031:   fclose(fic);
1.225     brouard  11032:   
1.136     brouard  11033:   return (0);
1.164     brouard  11034:   /* endread: */
1.225     brouard  11035:   printf("Exiting readdata: ");
                   11036:   fclose(fic);
                   11037:   return (1);
1.223     brouard  11038: }
1.126     brouard  11039: 
1.234     brouard  11040: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11041:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11042:   while (*p2 == ' ')
1.234     brouard  11043:     p2++; 
                   11044:   /* while ((*p1++ = *p2++) !=0) */
                   11045:   /*   ; */
                   11046:   /* do */
                   11047:   /*   while (*p2 == ' ') */
                   11048:   /*     p2++; */
                   11049:   /* while (*p1++ == *p2++); */
                   11050:   *stri=p2; 
1.145     brouard  11051: }
                   11052: 
1.330     brouard  11053: int decoderesult( char resultline[], int nres)
1.230     brouard  11054: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11055: {
1.235     brouard  11056:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11057:   char resultsav[MAXLINE];
1.330     brouard  11058:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11059:   /* int modelresult[MAXLINE]; */
1.230     brouard  11060:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11061: 
1.234     brouard  11062:   removefirstspace(&resultline);
1.332     brouard  11063:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11064: 
1.332     brouard  11065:   strcpy(resultsav,resultline);
1.342     brouard  11066:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11067:   if (strlen(resultsav) >1){
1.334     brouard  11068:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11069:   }
1.253     brouard  11070:   if(j == 0){ /* Resultline but no = */
                   11071:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11072:     return (0);
                   11073:   }
1.234     brouard  11074:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  11075:     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);
                   11076:     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  11077:     /* return 1;*/
1.234     brouard  11078:   }
1.334     brouard  11079:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11080:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11081:       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  11082:       /* 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  11083:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11084:       /* If a blank, then strc="V4=" and strd='\0' */
                   11085:       if(strc[0]=='\0'){
                   11086:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11087:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11088:        return 1;
                   11089:       }
1.234     brouard  11090:     }else
                   11091:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11092:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11093:     
1.230     brouard  11094:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11095:     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  11096:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11097:     /* cptcovsel++;     */
                   11098:     if (nbocc(stra,'=') >0)
                   11099:       strcpy(resultsav,stra); /* and analyzes it */
                   11100:   }
1.235     brouard  11101:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11102:   /* 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  11103:   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  11104:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11105:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11106:       match=0;
1.318     brouard  11107:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11108:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11109:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11110:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11111:          break;
                   11112:        }
                   11113:       }
                   11114:       if(match == 0){
1.338     brouard  11115:        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]);
                   11116:        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  11117:        return 1;
1.234     brouard  11118:       }
1.332     brouard  11119:     }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*/
                   11120:       /* We feed resultmodel[k1]=k2; */
                   11121:       match=0;
                   11122:       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 */
                   11123:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11124:          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  11125:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11126:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11127:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11128:          break;
                   11129:        }
                   11130:       }
                   11131:       if(match == 0){
1.338     brouard  11132:        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]);
                   11133:        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  11134:       return 1;
                   11135:       }
1.349   ! brouard  11136:     }else if(Typevar[k1]==2 || Typevar[k1]==3){ /* Product with or without age. We want to get the position in the resultline of the product in the model line*/
1.332     brouard  11137:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11138:       match=0;
1.342     brouard  11139:       /* 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  11140:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11141:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11142:          /* modelresult[k2]=k1; */
1.342     brouard  11143:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11144:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11145:        }
                   11146:       }
                   11147:       if(match == 0){
1.349   ! brouard  11148:        printf("Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
        !          11149:        fprintf(ficlog,"Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  11150:        return 1;
                   11151:       }
                   11152:       match=0;
                   11153:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11154:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11155:          /* modelresult[k2]=k1;*/
1.342     brouard  11156:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11157:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11158:          break;
                   11159:        }
                   11160:       }
                   11161:       if(match == 0){
1.349   ! brouard  11162:        printf("Error in result line (Product without age second variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
        !          11163:        fprintf(ficlog,"Error in result line (Product without age second variable or double product with age): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  11164:        return 1;
                   11165:       }
                   11166:     }/* End of testing */
1.333     brouard  11167:   }/* End loop cptcovt */
1.235     brouard  11168:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11169:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11170:   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)
                   11171:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11172:     match=0;
1.318     brouard  11173:     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  11174:       if(Typevar[k1]==0){ /* Single only */
1.349   ! brouard  11175:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11176:          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  11177:          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  11178:          ++match;
                   11179:        }
                   11180:       }
                   11181:     }
                   11182:     if(match == 0){
1.338     brouard  11183:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11184:       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  11185:       return 1;
1.234     brouard  11186:     }else if(match > 1){
1.338     brouard  11187:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11188:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11189:       return 1;
1.234     brouard  11190:     }
                   11191:   }
1.334     brouard  11192:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11193:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11194:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11195:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11196:   /* 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*/
                   11197:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11198:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11199:   /*    1 0 0 0 */
                   11200:   /*    2 1 0 0 */
                   11201:   /*    3 0 1 0 */ 
1.330     brouard  11202:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11203:   /*    5 0 0 1 */
1.330     brouard  11204:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11205:   /*    7 0 1 1 */
                   11206:   /*    8 1 1 1 */
1.237     brouard  11207:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11208:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11209:   /* V5*age V5 known which value for nres?  */
                   11210:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11211:   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.
                   11212:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11213:     /* k counting number of combination of single dummies in the equation model */
                   11214:     /* k4 counting single dummies in the equation model */
                   11215:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11216:     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  11217:        /* 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  11218:       /* 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  11219:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11220:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11221:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11222:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11223:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11224:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11225:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11226:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11227:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11228:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11229:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11230:       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  11231:       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  11232:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11233:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11234:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11235:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11236:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11237:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11238:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11239:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11240:       /* 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  11241:       k4++;;
1.331     brouard  11242:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11243:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11244:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11245:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11246:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11247:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11248:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11249:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11250:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11251:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11252:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11253:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11254:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11255:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11256:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11257:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11258:       /* 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  11259:       k4q++;;
1.331     brouard  11260:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11261:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11262:       /* Wrong we want the value of variable name Tvar[k1] */
                   11263:       
                   11264:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11265:       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  11266:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11267:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11268:       /* 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  11269:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11270:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11271:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11272:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11273:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11274:       /* 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.349   ! brouard  11275:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11276:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11277:       /* 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  11278:     }else{
1.332     brouard  11279:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11280:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11281:     }
                   11282:   }
1.234     brouard  11283:   
1.334     brouard  11284:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11285:   return (0);
                   11286: }
1.235     brouard  11287: 
1.230     brouard  11288: int decodemodel( char model[], int lastobs)
                   11289:  /**< This routine decodes the model and returns:
1.224     brouard  11290:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11291:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11292:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11293:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11294:        * - cptcovage number of covariates with age*products =2
                   11295:        * - cptcovs number of simple covariates
1.339     brouard  11296:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11297:        * - 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  11298:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11299:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11300:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11301:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11302:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11303:        */
1.319     brouard  11304: /* 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  11305: {
1.238     brouard  11306:   int i, j, k, ks, v;
1.349   ! brouard  11307:   int n,m;
        !          11308:   int  j1, k1, k11, k12, k2, k3, k4;
        !          11309:   char modelsav[300];
        !          11310:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11311:   char *strpt;
1.349   ! brouard  11312:   int  **existcomb;
        !          11313:   
        !          11314:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
        !          11315:   for(i=1;i<=NCOVMAX;i++)
        !          11316:     for(j=1;j<=NCOVMAX;j++)
        !          11317:       existcomb[i][j]=0;
        !          11318:     
1.145     brouard  11319:   /*removespace(model);*/
1.136     brouard  11320:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349   ! brouard  11321:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11322:     if (strstr(model,"AGE") !=0){
1.192     brouard  11323:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11324:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11325:       return 1;
                   11326:     }
1.141     brouard  11327:     if (strstr(model,"v") !=0){
1.338     brouard  11328:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11329:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11330:       return 1;
                   11331:     }
1.187     brouard  11332:     strcpy(modelsav,model); 
                   11333:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11334:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11335:       if(strpt != model){
1.338     brouard  11336:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11337:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11338:  corresponding column of parameters.\n",model);
1.338     brouard  11339:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11340:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11341:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11342:        return 1;
1.225     brouard  11343:       }
1.187     brouard  11344:       nagesqr=1;
                   11345:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11346:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11347:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11348:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11349:       else 
1.234     brouard  11350:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11351:     }else
                   11352:       nagesqr=0;
1.349   ! brouard  11353:     if (strlen(modelsav) >1){ /* V2 +V3 +V4 +V6 +V7 +V6*V2 +V7*V2 +V6*V3 +V7*V3 +V6*V4 +V7*V4 +age*V2 +age*V3 +age*V4 +age*V6 +age*V7 +age*V6*V2 +V7*V2 +age*V6*V3 +age*V7*V3 +age*V6*V4 +age*V7*V4 */
1.187     brouard  11354:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11355:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.349   ! brouard  11356:       cptcovs=j+1-j1; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  */
1.187     brouard  11357:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11358:                     * cst, age and age*age 
                   11359:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11360:       /* including age products which are counted in cptcovage.
                   11361:        * but the covariates which are products must be treated 
                   11362:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349   ! brouard  11363:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
        !          11364:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11365:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349   ! brouard  11366:       cptcovprodage=0;
        !          11367:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11368:       
1.187     brouard  11369:       /*   Design
                   11370:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11371:        *  <          ncovcol=8                >
                   11372:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11373:        *   k=  1    2      3       4     5       6      7        8
                   11374:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11375:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11376:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11377:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11378:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11379:        *  Tage[++cptcovage]=k
1.345     brouard  11380:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11381:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11382:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11383:        *  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
                   11384:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11385:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11386:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11387:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11388:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11389:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11390:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11391:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11392:        * p Tprod[1]@2={                         6, 5}
                   11393:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11394:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11395:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11396:        *How to reorganize? Tvars(orted)
1.187     brouard  11397:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11398:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11399:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11400:        * Struct []
                   11401:        */
1.225     brouard  11402:       
1.187     brouard  11403:       /* This loop fills the array Tvar from the string 'model'.*/
                   11404:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11405:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11406:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11407:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11408:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11409:       /*       k=1 Tvar[1]=2 (from V2) */
                   11410:       /*       k=5 Tvar[5] */
                   11411:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11412:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11413:       /*       } */
1.198     brouard  11414:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11415:       /*
                   11416:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11417:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11418:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11419:       }
1.187     brouard  11420:       cptcovage=0;
1.319     brouard  11421:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11422:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11423:                                         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" */
                   11424:        if (nbocc(modelsav,'+')==0)
                   11425:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11426:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11427:        /*scanf("%d",i);*/
1.349   ! brouard  11428:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age OR double product with age strb=age*V6*V2 or V6*V2*age or V6*age*V2 */
        !          11429:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 OR strb=age*V6*V2 strc=V6*V2 strd=age OR c=V2*age OR c=age*V2  */
        !          11430:          if(strchr(strc,'*')) { /**< Model with age and DOUBLE product: allowed since 0.99r44, strc=V6*V2 or V2*age or age*V2, strd=age or V6 or V6   */
        !          11431:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
        !          11432:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
        !          11433:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
        !          11434:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
        !          11435:              /* We want strb=Vn*Vm */
        !          11436:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
        !          11437:                 strcpy(strb,strd);
        !          11438:                 strcat(strb,"*");
        !          11439:                 strcat(strb,stre);
        !          11440:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
        !          11441:                 strcpy(strb,strf);
        !          11442:                 strcat(strb,"*");
        !          11443:                 strcat(strb,stre);
        !          11444:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
        !          11445:               }
        !          11446:              printf("DEBUG FIXED k=%d, Tage[k]=%d, Tvar[Tage[k]=%d,FixedV[Tvar[Tage[k]]]=%d\n",k,Tage[k],Tvar[Tage[k]],FixedV[Tvar[Tage[k]]]);
        !          11447:              FixedV[Tvar[Tage[k]]]=0; /* HERY not sure */
        !          11448:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
        !          11449:              strcpy(stre,strb); /* save full b in stre */
        !          11450:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
        !          11451:              strcpy(strf,strc); /* save short c in new short f */
        !          11452:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
        !          11453:              /* strcpy(strc,stre);*/ /* save full e in c for future */
        !          11454:             }
        !          11455:             cptcovdageprod++; /* double product with age  Which product is it? */
        !          11456:             /* strcpy(strb,strc);  /\* strb was age*V6*V2 or V6*V2*age or V6*age*V2 IS now V6*V2 or V2*age or age*V2 *\/ */
        !          11457:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11458:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349   ! brouard  11459:            n=atoi(stre);
1.234     brouard  11460:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349   ! brouard  11461:            m=atoi(strc);
        !          11462:            cptcovage++; /* Counts the number of covariates which include age as a product */
        !          11463:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
        !          11464:            if(existcomb[n][m] == 0){
        !          11465:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
        !          11466:              printf("Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
        !          11467:              fprintf(ficlog,"Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
        !          11468:              fflush(ficlog);
        !          11469:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
        !          11470:              k12++;
        !          11471:              existcomb[n][m]=k1;
        !          11472:              existcomb[m][n]=k1;
        !          11473:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
        !          11474:              Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2+ age*V6*V3 Gives the k position of the k1 double product Vn*Vm or age*Vn*Vm*/
        !          11475:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
        !          11476:              Tvard[k1][1] =m; /* m 1 for V1*/
        !          11477:              Tvardk[k][1] =m; /* m 1 for V1*/
        !          11478:              Tvard[k1][2] =n; /* n 4 for V4*/
        !          11479:              Tvardk[k][2] =n; /* n 4 for V4*/
        !          11480: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */
        !          11481:              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 */
        !          11482:                for (i=1; i<=lastobs;i++){/* For fixed product */
        !          11483:                  /* Computes the new covariate which is a product of
        !          11484:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          11485:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          11486:                }
        !          11487:                cptcovprodage++; /* Counting the number of fixed covariate with age */
        !          11488:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
        !          11489:                k12++;
        !          11490:                FixedV[ncovcolt+k12]=0;
        !          11491:              }else{ /*End of FixedV */
        !          11492:                cptcovprodvage++; /* Counting the number of varying covariate with age */
        !          11493:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
        !          11494:                k12++;
        !          11495:                FixedV[ncovcolt+k12]=1;
        !          11496:              }
        !          11497:            }else{  /* k1 Vn*Vm already exists */
        !          11498:              k11=existcomb[n][m];
        !          11499:              Tposprod[k]=k11; /* OK */
        !          11500:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
        !          11501:              Tvardk[k][1]=m;
        !          11502:              Tvardk[k][2]=n;
        !          11503:              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 */
        !          11504:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
        !          11505:                cptcovprodage++; /* Counting the number of fixed covariate with age */
        !          11506:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
        !          11507:                Tvar[Tage[cptcovage]]=k1;
        !          11508:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
        !          11509:                k12++;
        !          11510:                FixedV[ncovcolt+k12]=0;
        !          11511:              }else{ /* Already exists but time varying (and age) */
        !          11512:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
        !          11513:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
        !          11514:                /* Tvar[Tage[cptcovage]]=k1; */
        !          11515:                cptcovprodvage++;
        !          11516:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
        !          11517:                k12++;
        !          11518:                FixedV[ncovcolt+k12]=1;
        !          11519:              }
        !          11520:            }
        !          11521:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
        !          11522:            /* Tvar[k]=k11; /\* HERY *\/ */
        !          11523:          } else {/* simple product strb=age*Vn so that c=Vn and d=age, or strb=Vn*age so that c=age and d=Vn, or b=Vn*Vm so that c=Vm and d=Vn */
        !          11524:             cptcovprod++;
        !          11525:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
        !          11526:               /* covar is not filled and then is empty */
        !          11527:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          11528:               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 */
        !          11529:               Typevar[k]=1;  /* 1 for age product */
        !          11530:               cptcovage++; /* Counts the number of covariates which include age as a product */
        !          11531:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
        !          11532:              if( FixedV[Tvar[k]] == 0){
        !          11533:                cptcovprodage++; /* Counting the number of fixed covariate with age */
        !          11534:              }else{
        !          11535:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
        !          11536:              }
        !          11537:               /*printf("stre=%s ", stre);*/
        !          11538:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
        !          11539:               cutl(stre,strb,strc,'V');
        !          11540:               Tvar[k]=atoi(stre);
        !          11541:               Typevar[k]=1;  /* 1 for age product */
        !          11542:               cptcovage++;
        !          11543:               Tage[cptcovage]=k;
        !          11544:              if( FixedV[Tvar[k]] == 0){
        !          11545:                cptcovprodage++; /* Counting the number of fixed covariate with age */
        !          11546:              }else{
        !          11547:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11548:              }
1.349   ! brouard  11549:             }else{ /*  for product Vn*Vm */
        !          11550:              Typevar[k]=2;  /* 2 for product Vn*Vm */
        !          11551:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          11552:              n=atoi(stre);
        !          11553:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          11554:              m=atoi(strc);
        !          11555:              k1++;
        !          11556:              cptcovprodnoage++;
        !          11557:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
        !          11558:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
        !          11559:                fprintf(ficlog,"Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
        !          11560:                fflush(ficlog);
        !          11561:                k11=existcomb[n][m];
        !          11562:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
        !          11563:                Tposprod[k]=k11;
        !          11564:                Tprod[k11]=k;
        !          11565:                Tvardk[k][1] =m; /* m 1 for V1*/
        !          11566:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
        !          11567:                Tvardk[k][2] =n; /* n 4 for V4*/                
        !          11568:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
        !          11569:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
        !          11570:                existcomb[n][m]=k1;
        !          11571:                existcomb[m][n]=k1;
        !          11572:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
        !          11573:                                                    because this model-covariate is a construction we invent a new column
        !          11574:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
        !          11575:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
        !          11576:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
        !          11577:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
        !          11578:                /* Please remark that the new variables are model dependent */
        !          11579:                /* If we have 4 variable but the model uses only 3, like in
        !          11580:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
        !          11581:                 *  k=     1     2      3   4     5        6        7       8
        !          11582:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
        !          11583:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
        !          11584:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
        !          11585:                 */
        !          11586:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
        !          11587:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
        !          11588:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
        !          11589:                Tvard[k1][1] =m; /* m 1 for V1*/
        !          11590:                Tvardk[k][1] =m; /* m 1 for V1*/
        !          11591:                Tvard[k1][2] =n; /* n 4 for V4*/
        !          11592:                Tvardk[k][2] =n; /* n 4 for V4*/
        !          11593:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
        !          11594:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
        !          11595:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
        !          11596:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
        !          11597:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
        !          11598:                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 */
        !          11599:                  for (i=1; i<=lastobs;i++){/* For fixed product */
        !          11600:                    /* Computes the new covariate which is a product of
        !          11601:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          11602:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          11603:                  }
        !          11604:                  /* TvarVV[k2]=n; */
        !          11605:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11606:                  /* TvarVV[k2+1]=m; */
        !          11607:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11608:                }else{ /* not FixedV */
        !          11609:                  /* TvarVV[k2]=n; */
        !          11610:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11611:                  /* TvarVV[k2+1]=m; */
        !          11612:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11613:                }                 
        !          11614:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
        !          11615:            } /*  End of product Vn*Vm */
        !          11616:           } /* End of age*double product or simple product */
        !          11617:        }else { /* not a product */
1.234     brouard  11618:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11619:          /*  scanf("%d",i);*/
                   11620:          cutl(strd,strc,strb,'V');
                   11621:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11622:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11623:          Tvar[k]=atoi(strd);
                   11624:          Typevar[k]=0;  /* 0 for simple covariates */
                   11625:        }
                   11626:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11627:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11628:                                  scanf("%d",i);*/
1.187     brouard  11629:       } /* end of loop + on total covariates */
                   11630:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11631:   } /* end if strlen(model == 0) */
1.349   ! brouard  11632:   cptcovs=cptcovt - cptcovdageprod - cptcovprod;/**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age + age*v4*V3=> V1 + V3 =4+1-3=2  */
        !          11633: 
1.136     brouard  11634:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11635:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11636:   
1.136     brouard  11637:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11638:      printf("cptcovprod=%d ", cptcovprod);
                   11639:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11640:      scanf("%d ",i);*/
                   11641: 
                   11642: 
1.230     brouard  11643: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11644:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11645: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11646:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11647:    k =           1    2   3     4       5       6      7      8        9
                   11648:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11649:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11650:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11651:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11652:          Tmodelind[combination of covar]=k;
1.225     brouard  11653: */  
                   11654: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11655:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11656:   /* 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  11657:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11658:   printf("Model=1+age+%s\n\
1.349   ! brouard  11659: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
1.227     brouard  11660: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11661: 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  11662:   fprintf(ficlog,"Model=1+age+%s\n\
1.349   ! brouard  11663: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
1.227     brouard  11664: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11665: 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  11666:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11667:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.349   ! brouard  11668:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0,ncovva=0,ncovvta=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  11669:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11670:       Fixed[k]= 0;
                   11671:       Dummy[k]= 0;
1.225     brouard  11672:       ncoveff++;
1.232     brouard  11673:       ncovf++;
1.234     brouard  11674:       nsd++;
                   11675:       modell[k].maintype= FTYPE;
                   11676:       TvarsD[nsd]=Tvar[k];
                   11677:       TvarsDind[nsd]=k;
1.330     brouard  11678:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11679:       TvarF[ncovf]=Tvar[k];
                   11680:       TvarFind[ncovf]=k;
                   11681:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11682:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11683:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
1.240     brouard  11684:     }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  11685:       Fixed[k]= 0;
                   11686:       Dummy[k]= 1;
1.230     brouard  11687:       nqfveff++;
1.234     brouard  11688:       modell[k].maintype= FTYPE;
                   11689:       modell[k].subtype= FQ;
                   11690:       nsq++;
1.334     brouard  11691:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11692:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11693:       ncovf++;
1.234     brouard  11694:       TvarF[ncovf]=Tvar[k];
                   11695:       TvarFind[ncovf]=k;
1.231     brouard  11696:       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  11697:       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  11698:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11699:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11700:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11701:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11702:       ncovvt++;
                   11703:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11704:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11705: 
1.227     brouard  11706:       Fixed[k]= 1;
                   11707:       Dummy[k]= 0;
1.225     brouard  11708:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11709:       modell[k].maintype= VTYPE;
                   11710:       modell[k].subtype= VD;
                   11711:       nsd++;
                   11712:       TvarsD[nsd]=Tvar[k];
                   11713:       TvarsDind[nsd]=k;
1.330     brouard  11714:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11715:       ncovv++; /* Only simple time varying variables */
                   11716:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11717:       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  11718:       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 */
                   11719:       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  11720:       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);
                   11721:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11722:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11723:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11724:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11725:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11726:       ncovvt++;
                   11727:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11728:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11729:       
1.234     brouard  11730:       Fixed[k]= 1;
                   11731:       Dummy[k]= 1;
                   11732:       nqtveff++;
                   11733:       modell[k].maintype= VTYPE;
                   11734:       modell[k].subtype= VQ;
                   11735:       ncovv++; /* Only simple time varying variables */
                   11736:       nsq++;
1.334     brouard  11737:       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) */
                   11738:       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  11739:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11740:       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  11741:       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 */
                   11742:       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  11743:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11744:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349   ! brouard  11745:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%Ad,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
1.342     brouard  11746:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11747:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11748:       ncova++;
                   11749:       TvarA[ncova]=Tvar[k];
                   11750:       TvarAind[ncova]=k;
1.349   ! brouard  11751:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
        !          11752:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.231     brouard  11753:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11754:        Fixed[k]= 2;
                   11755:        Dummy[k]= 2;
                   11756:        modell[k].maintype= ATYPE;
                   11757:        modell[k].subtype= APFD;
1.349   ! brouard  11758:        ncovta++;
        !          11759:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
        !          11760:        TvarAVVAind[ncovta]=k;
1.240     brouard  11761:        /* ncoveff++; */
1.227     brouard  11762:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11763:        Fixed[k]= 2;
                   11764:        Dummy[k]= 3;
                   11765:        modell[k].maintype= ATYPE;
                   11766:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349   ! brouard  11767:        ncovta++;
        !          11768:        TvarAVVA[ncovta]=Tvar[k]; /*   */
        !          11769:        TvarAVVAind[ncovta]=k;
1.240     brouard  11770:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11771:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11772:        Fixed[k]= 3;
                   11773:        Dummy[k]= 2;
                   11774:        modell[k].maintype= ATYPE;
                   11775:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349   ! brouard  11776:        ncovva++;
        !          11777:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
        !          11778:        TvarVVAind[ncovva]=k;
        !          11779:        ncovta++;
        !          11780:        TvarAVVA[ncovta]=Tvar[k]; /*   */
        !          11781:        TvarAVVAind[ncovta]=k;
1.240     brouard  11782:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11783:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11784:        Fixed[k]= 3;
                   11785:        Dummy[k]= 3;
                   11786:        modell[k].maintype= ATYPE;
                   11787:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349   ! brouard  11788:        ncovva++;
        !          11789:        TvarVVA[ncovva]=Tvar[k]; /*   */
        !          11790:        TvarVVAind[ncovva]=k;
        !          11791:        ncovta++;
        !          11792:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
        !          11793:        TvarAVVAind[ncovta]=k;
1.240     brouard  11794:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11795:       }
1.349   ! brouard  11796:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
        !          11797:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
        !          11798:       if(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 V3*V2 */
        !          11799:       printf("MEMORY ERRORR k=%d Tvardk[k][1]=%d, Tvardk[k][2]=%d, FixedV[Tvardk[k][1]]=%d,FixedV[Tvardk[k][2]]=%d\n ",k,Tvardk[k][1],Tvardk[k][2],FixedV[Tvardk[k][1]],FixedV[Tvardk[k][2]]);
        !          11800:        Fixed[k]= 0;
        !          11801:        Dummy[k]= 0;
        !          11802:        ncoveff++;
        !          11803:        ncovf++;
        !          11804:        /* ncovv++; */
        !          11805:        /* TvarVV[ncovv]=Tvardk[k][1]; */
        !          11806:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11807:        /* ncovv++; */
        !          11808:        /* TvarVV[ncovv]=Tvardk[k][2]; */
        !          11809:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
        !          11810:        modell[k].maintype= FTYPE;
        !          11811:        TvarF[ncovf]=Tvar[k];
        !          11812:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
        !          11813:        TvarFind[ncovf]=k;
        !          11814:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          11815:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          11816:       }else{/* product varying 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  */
        !          11817:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          11818:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
        !          11819:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          11820:        k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
        !          11821:        ncovvt++;
        !          11822:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
        !          11823:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
        !          11824:        ncovvt++;
        !          11825:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
        !          11826:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
        !          11827:        
        !          11828:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
        !          11829:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
        !          11830:        
        !          11831:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
        !          11832:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
        !          11833:            Fixed[k]= 1;
        !          11834:            Dummy[k]= 0;
        !          11835:            modell[k].maintype= FTYPE;
        !          11836:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
        !          11837:            ncovf++; /* Fixed variables without age */
        !          11838:            TvarF[ncovf]=Tvar[k];
        !          11839:            TvarFind[ncovf]=k;
        !          11840:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
        !          11841:            Fixed[k]= 0;  /* Fixed product */
        !          11842:            Dummy[k]= 1;
        !          11843:            modell[k].maintype= FTYPE;
        !          11844:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
        !          11845:            ncovf++; /* Varying variables without age */
        !          11846:            TvarF[ncovf]=Tvar[k];
        !          11847:            TvarFind[ncovf]=k;
        !          11848:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
        !          11849:            Fixed[k]= 1;
        !          11850:            Dummy[k]= 0;
        !          11851:            modell[k].maintype= VTYPE;
        !          11852:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
        !          11853:            ncovv++; /* Varying variables without age */
        !          11854:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
        !          11855:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
        !          11856:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
        !          11857:            Fixed[k]= 1;
        !          11858:            Dummy[k]= 1;
        !          11859:            modell[k].maintype= VTYPE;
        !          11860:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
        !          11861:            ncovv++; /* Varying variables without age */
        !          11862:            TvarV[ncovv]=Tvar[k];
        !          11863:            TvarVind[ncovv]=k;
        !          11864:          }
        !          11865:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
        !          11866:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
        !          11867:            Fixed[k]= 0;  /*  Fixed product */
        !          11868:            Dummy[k]= 1;
        !          11869:            modell[k].maintype= FTYPE;
        !          11870:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
        !          11871:            ncovf++; /* Fixed variables without age */
        !          11872:            TvarF[ncovf]=Tvar[k];
        !          11873:            TvarFind[ncovf]=k;
        !          11874:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
        !          11875:            Fixed[k]= 1;
        !          11876:            Dummy[k]= 1;
        !          11877:            modell[k].maintype= VTYPE;
        !          11878:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
        !          11879:            ncovv++; /* Varying variables without age */
        !          11880:            TvarV[ncovv]=Tvar[k];
        !          11881:            TvarVind[ncovv]=k;
        !          11882:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
        !          11883:            Fixed[k]= 1;
        !          11884:            Dummy[k]= 1;
        !          11885:            modell[k].maintype= VTYPE;
        !          11886:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
        !          11887:            ncovv++; /* Varying variables without age */
        !          11888:            TvarV[ncovv]=Tvar[k];
        !          11889:            TvarVind[ncovv]=k;
        !          11890:            ncovv++; /* Varying variables without age */
        !          11891:            TvarV[ncovv]=Tvar[k];
        !          11892:            TvarVind[ncovv]=k;
        !          11893:          }
        !          11894:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
        !          11895:          if(Tvard[k1][2] <=ncovcol){
        !          11896:            Fixed[k]= 1;
        !          11897:            Dummy[k]= 1;
        !          11898:            modell[k].maintype= VTYPE;
        !          11899:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
        !          11900:            ncovv++; /* Varying variables without age */
        !          11901:            TvarV[ncovv]=Tvar[k];
        !          11902:            TvarVind[ncovv]=k;
        !          11903:          }else if(Tvard[k1][2] <=ncovcol+nqv){
        !          11904:            Fixed[k]= 1;
        !          11905:            Dummy[k]= 1;
        !          11906:            modell[k].maintype= VTYPE;
        !          11907:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
        !          11908:            ncovv++; /* Varying variables without age */
        !          11909:            TvarV[ncovv]=Tvar[k];
        !          11910:            TvarVind[ncovv]=k;
        !          11911:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          11912:            Fixed[k]= 1;
        !          11913:            Dummy[k]= 0;
        !          11914:            modell[k].maintype= VTYPE;
        !          11915:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
        !          11916:            ncovv++; /* Varying variables without age */
        !          11917:            TvarV[ncovv]=Tvar[k];
        !          11918:            TvarVind[ncovv]=k;
        !          11919:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          11920:            Fixed[k]= 1;
        !          11921:            Dummy[k]= 1;
        !          11922:            modell[k].maintype= VTYPE;
        !          11923:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
        !          11924:            ncovv++; /* Varying variables without age */
        !          11925:            TvarV[ncovv]=Tvar[k];
        !          11926:            TvarVind[ncovv]=k;
        !          11927:          }
        !          11928:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
        !          11929:          if(Tvard[k1][2] <=ncovcol){
        !          11930:            Fixed[k]= 1;
        !          11931:            Dummy[k]= 1;
        !          11932:            modell[k].maintype= VTYPE;
        !          11933:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
        !          11934:            ncovv++; /* Varying variables without age */
        !          11935:            TvarV[ncovv]=Tvar[k];
        !          11936:            TvarVind[ncovv]=k;
        !          11937:          }else if(Tvard[k1][2] <=ncovcol+nqv){
        !          11938:            Fixed[k]= 1;
        !          11939:            Dummy[k]= 1;
        !          11940:            modell[k].maintype= VTYPE;
        !          11941:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
        !          11942:            ncovv++; /* Varying variables without age */
        !          11943:            TvarV[ncovv]=Tvar[k];
        !          11944:            TvarVind[ncovv]=k;
        !          11945:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
        !          11946:            Fixed[k]= 1;
        !          11947:            Dummy[k]= 1;
        !          11948:            modell[k].maintype= VTYPE;
        !          11949:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
        !          11950:            ncovv++; /* Varying variables without age */
        !          11951:            TvarV[ncovv]=Tvar[k];
        !          11952:            TvarVind[ncovv]=k;
        !          11953:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
        !          11954:            Fixed[k]= 1;
        !          11955:            Dummy[k]= 1;
        !          11956:            modell[k].maintype= VTYPE;
        !          11957:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
        !          11958:            ncovv++; /* Varying variables without age */
        !          11959:            TvarV[ncovv]=Tvar[k];
        !          11960:            TvarVind[ncovv]=k;
        !          11961:          }
        !          11962:        }else{
        !          11963:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
        !          11964:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
        !          11965:        } /*end k1*/
        !          11966:       }
        !          11967:     }else if(Typevar[k] == 3){  /* product Vn * Vm with 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  */
1.339     brouard  11968:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349   ! brouard  11969:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
        !          11970:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          11971:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
        !          11972:       ncova++;
        !          11973:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
        !          11974:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
        !          11975:       ncova++;
        !          11976:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
        !          11977:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  11978: 
1.349   ! brouard  11979:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
        !          11980:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
        !          11981:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
        !          11982:        ncovta++;
        !          11983:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
        !          11984:        TvarAVVAind[ncovta]=k;
        !          11985:        ncovta++;
        !          11986:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
        !          11987:        TvarAVVAind[ncovta]=k;
        !          11988:       }else{
        !          11989:        ncovva++;  /* HERY  reached */
        !          11990:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
        !          11991:        TvarVVAind[ncovva]=k;
        !          11992:        ncovva++;
        !          11993:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
        !          11994:        TvarVVAind[ncovva]=k;
        !          11995:        ncovta++;
        !          11996:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
        !          11997:        TvarAVVAind[ncovta]=k;
        !          11998:        ncovta++;
        !          11999:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
        !          12000:        TvarAVVAind[ncovta]=k;
        !          12001:       }
1.339     brouard  12002:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12003:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349   ! brouard  12004:          Fixed[k]= 2;
        !          12005:          Dummy[k]= 2;
1.240     brouard  12006:          modell[k].maintype= FTYPE;
                   12007:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349   ! brouard  12008:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
        !          12009:          /* TvarFind[ncova]=k; */
1.339     brouard  12010:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349   ! brouard  12011:          Fixed[k]= 2;  /* Fixed product */
        !          12012:          Dummy[k]= 3;
1.240     brouard  12013:          modell[k].maintype= FTYPE;
                   12014:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349   ! brouard  12015:          /* TvarF[ncova]=Tvar[k]; */
        !          12016:          /* TvarFind[ncova]=k; */
1.339     brouard  12017:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349   ! brouard  12018:          Fixed[k]= 3;
        !          12019:          Dummy[k]= 2;
1.240     brouard  12020:          modell[k].maintype= VTYPE;
                   12021:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349   ! brouard  12022:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
        !          12023:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12024:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349   ! brouard  12025:          Fixed[k]= 3;
        !          12026:          Dummy[k]= 3;
1.240     brouard  12027:          modell[k].maintype= VTYPE;
                   12028:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349   ! brouard  12029:          /* ncovv++; /\* Varying variables without age *\/ */
        !          12030:          /* TvarV[ncovv]=Tvar[k]; */
        !          12031:          /* TvarVind[ncovv]=k; */
1.240     brouard  12032:        }
1.339     brouard  12033:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12034:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349   ! brouard  12035:          Fixed[k]= 2;  /*  Fixed product */
        !          12036:          Dummy[k]= 2;
1.240     brouard  12037:          modell[k].maintype= FTYPE;
                   12038:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349   ! brouard  12039:          /* ncova++; /\* Fixed variables with age *\/ */
        !          12040:          /* TvarF[ncovf]=Tvar[k]; */
        !          12041:          /* TvarFind[ncovf]=k; */
1.339     brouard  12042:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349   ! brouard  12043:          Fixed[k]= 2;
        !          12044:          Dummy[k]= 3;
1.240     brouard  12045:          modell[k].maintype= VTYPE;
                   12046:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349   ! brouard  12047:          /* ncova++; /\* Varying variables with age *\/ */
        !          12048:          /* TvarV[ncova]=Tvar[k]; */
        !          12049:          /* TvarVind[ncova]=k; */
1.339     brouard  12050:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349   ! brouard  12051:          Fixed[k]= 3;
        !          12052:          Dummy[k]= 2;
1.240     brouard  12053:          modell[k].maintype= VTYPE;
                   12054:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349   ! brouard  12055:          ncova++; /* Varying variables without age */
        !          12056:          TvarV[ncova]=Tvar[k];
        !          12057:          TvarVind[ncova]=k;
        !          12058:          /* ncova++; /\* Varying variables without age *\/ */
        !          12059:          /* TvarV[ncova]=Tvar[k]; */
        !          12060:          /* TvarVind[ncova]=k; */
1.240     brouard  12061:        }
1.339     brouard  12062:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12063:        if(Tvard[k1][2] <=ncovcol){
1.349   ! brouard  12064:          Fixed[k]= 2;
        !          12065:          Dummy[k]= 2;
1.240     brouard  12066:          modell[k].maintype= VTYPE;
                   12067:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349   ! brouard  12068:          /* ncova++; /\* Varying variables with age *\/ */
        !          12069:          /* TvarV[ncova]=Tvar[k]; */
        !          12070:          /* TvarVind[ncova]=k; */
1.240     brouard  12071:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349   ! brouard  12072:          Fixed[k]= 2;
        !          12073:          Dummy[k]= 3;
1.240     brouard  12074:          modell[k].maintype= VTYPE;
                   12075:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349   ! brouard  12076:          /* ncova++; /\* Varying variables with age *\/ */
        !          12077:          /* TvarV[ncova]=Tvar[k]; */
        !          12078:          /* TvarVind[ncova]=k; */
1.240     brouard  12079:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349   ! brouard  12080:          Fixed[k]= 3;
        !          12081:          Dummy[k]= 2;
1.240     brouard  12082:          modell[k].maintype= VTYPE;
                   12083:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349   ! brouard  12084:          /* ncova++; /\* Varying variables with age *\/ */
        !          12085:          /* TvarV[ncova]=Tvar[k]; */
        !          12086:          /* TvarVind[ncova]=k; */
1.240     brouard  12087:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349   ! brouard  12088:          Fixed[k]= 3;
        !          12089:          Dummy[k]= 3;
1.240     brouard  12090:          modell[k].maintype= VTYPE;
                   12091:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349   ! brouard  12092:          /* ncova++; /\* Varying variables with age *\/ */
        !          12093:          /* TvarV[ncova]=Tvar[k]; */
        !          12094:          /* TvarVind[ncova]=k; */
1.240     brouard  12095:        }
1.339     brouard  12096:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12097:        if(Tvard[k1][2] <=ncovcol){
1.349   ! brouard  12098:          Fixed[k]= 2;
        !          12099:          Dummy[k]= 2;
1.240     brouard  12100:          modell[k].maintype= VTYPE;
                   12101:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349   ! brouard  12102:          /* ncova++; /\* Varying variables with age *\/ */
        !          12103:          /* TvarV[ncova]=Tvar[k]; */
        !          12104:          /* TvarVind[ncova]=k; */
1.240     brouard  12105:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349   ! brouard  12106:          Fixed[k]= 2;
        !          12107:          Dummy[k]= 3;
1.240     brouard  12108:          modell[k].maintype= VTYPE;
                   12109:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349   ! brouard  12110:          /* ncova++; /\* Varying variables with age *\/ */
        !          12111:          /* TvarV[ncova]=Tvar[k]; */
        !          12112:          /* TvarVind[ncova]=k; */
1.240     brouard  12113:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349   ! brouard  12114:          Fixed[k]= 3;
        !          12115:          Dummy[k]= 2;
1.240     brouard  12116:          modell[k].maintype= VTYPE;
                   12117:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349   ! brouard  12118:          /* ncova++; /\* Varying variables with age *\/ */
        !          12119:          /* TvarV[ncova]=Tvar[k]; */
        !          12120:          /* TvarVind[ncova]=k; */
1.240     brouard  12121:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349   ! brouard  12122:          Fixed[k]= 3;
        !          12123:          Dummy[k]= 3;
1.240     brouard  12124:          modell[k].maintype= VTYPE;
                   12125:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349   ! brouard  12126:          /* ncova++; /\* Varying variables with age *\/ */
        !          12127:          /* TvarV[ncova]=Tvar[k]; */
        !          12128:          /* TvarVind[ncova]=k; */
1.240     brouard  12129:        }
1.227     brouard  12130:       }else{
1.240     brouard  12131:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12132:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12133:       } /*end k1*/
1.349   ! brouard  12134:     } else{
1.226     brouard  12135:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12136:       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  12137:     }
1.342     brouard  12138:     /* 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]); */
                   12139:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12140:     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]);
                   12141:   }
1.349   ! brouard  12142:   ncovvta=ncovva;
1.227     brouard  12143:   /* Searching for doublons in the model */
                   12144:   for(k1=1; k1<= cptcovt;k1++){
                   12145:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12146:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12147:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12148:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12149:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12150:            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]);
                   12151:            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  12152:            return(1);
                   12153:          }
                   12154:        }else if (Typevar[k1] ==2){
                   12155:          k3=Tposprod[k1];
                   12156:          k4=Tposprod[k2];
                   12157:          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  12158:            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]]);
                   12159:            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  12160:            return(1);
                   12161:          }
                   12162:        }
1.227     brouard  12163:       }
                   12164:     }
1.225     brouard  12165:   }
                   12166:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12167:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12168:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12169:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349   ! brouard  12170: 
        !          12171:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12172:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12173:   /*endread:*/
1.225     brouard  12174:   printf("Exiting decodemodel: ");
                   12175:   return (1);
1.136     brouard  12176: }
                   12177: 
1.169     brouard  12178: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12179: {/* Check ages at death */
1.136     brouard  12180:   int i, m;
1.218     brouard  12181:   int firstone=0;
                   12182:   
1.136     brouard  12183:   for (i=1; i<=imx; i++) {
                   12184:     for(m=2; (m<= maxwav); m++) {
                   12185:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12186:        anint[m][i]=9999;
1.216     brouard  12187:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12188:          s[m][i]=-1;
1.136     brouard  12189:       }
                   12190:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12191:        *nberr = *nberr + 1;
1.218     brouard  12192:        if(firstone == 0){
                   12193:          firstone=1;
1.260     brouard  12194:        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  12195:        }
1.262     brouard  12196:        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  12197:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12198:       }
                   12199:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12200:        (*nberr)++;
1.259     brouard  12201:        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  12202:        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  12203:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12204:       }
                   12205:     }
                   12206:   }
                   12207: 
                   12208:   for (i=1; i<=imx; i++)  {
                   12209:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12210:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12211:       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  12212:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12213:          if(agedc[i]>0){
                   12214:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12215:              agev[m][i]=agedc[i];
1.214     brouard  12216:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12217:            }else {
1.136     brouard  12218:              if ((int)andc[i]!=9999){
                   12219:                nbwarn++;
                   12220:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12221:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12222:                agev[m][i]=-1;
                   12223:              }
                   12224:            }
1.169     brouard  12225:          } /* agedc > 0 */
1.214     brouard  12226:        } /* end if */
1.136     brouard  12227:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12228:                                 years but with the precision of a month */
                   12229:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12230:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12231:            agev[m][i]=1;
                   12232:          else if(agev[m][i] < *agemin){ 
                   12233:            *agemin=agev[m][i];
                   12234:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12235:          }
                   12236:          else if(agev[m][i] >*agemax){
                   12237:            *agemax=agev[m][i];
1.156     brouard  12238:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12239:          }
                   12240:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12241:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12242:        } /* en if 9*/
1.136     brouard  12243:        else { /* =9 */
1.214     brouard  12244:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12245:          agev[m][i]=1;
                   12246:          s[m][i]=-1;
                   12247:        }
                   12248:       }
1.214     brouard  12249:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12250:        agev[m][i]=1;
1.214     brouard  12251:       else{
                   12252:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12253:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12254:        agev[m][i]=0;
                   12255:       }
                   12256:     } /* End for lastpass */
                   12257:   }
1.136     brouard  12258:     
                   12259:   for (i=1; i<=imx; i++)  {
                   12260:     for(m=firstpass; (m<=lastpass); m++){
                   12261:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12262:        (*nberr)++;
1.136     brouard  12263:        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);     
                   12264:        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);     
                   12265:        return 1;
                   12266:       }
                   12267:     }
                   12268:   }
                   12269: 
                   12270:   /*for (i=1; i<=imx; i++){
                   12271:   for (m=firstpass; (m<lastpass); m++){
                   12272:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12273: }
                   12274: 
                   12275: }*/
                   12276: 
                   12277: 
1.139     brouard  12278:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12279:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12280: 
                   12281:   return (0);
1.164     brouard  12282:  /* endread:*/
1.136     brouard  12283:     printf("Exiting calandcheckages: ");
                   12284:     return (1);
                   12285: }
                   12286: 
1.172     brouard  12287: #if defined(_MSC_VER)
                   12288: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12289: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12290: //#include "stdafx.h"
                   12291: //#include <stdio.h>
                   12292: //#include <tchar.h>
                   12293: //#include <windows.h>
                   12294: //#include <iostream>
                   12295: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12296: 
                   12297: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12298: 
                   12299: BOOL IsWow64()
                   12300: {
                   12301:        BOOL bIsWow64 = FALSE;
                   12302: 
                   12303:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12304:        //  (HANDLE, PBOOL);
                   12305: 
                   12306:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12307: 
                   12308:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12309:        const char funcName[] = "IsWow64Process";
                   12310:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12311:                GetProcAddress(module, funcName);
                   12312: 
                   12313:        if (NULL != fnIsWow64Process)
                   12314:        {
                   12315:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12316:                        &bIsWow64))
                   12317:                        //throw std::exception("Unknown error");
                   12318:                        printf("Unknown error\n");
                   12319:        }
                   12320:        return bIsWow64 != FALSE;
                   12321: }
                   12322: #endif
1.177     brouard  12323: 
1.191     brouard  12324: void syscompilerinfo(int logged)
1.292     brouard  12325: {
                   12326: #include <stdint.h>
                   12327: 
                   12328:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12329:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12330:    /* /GS /W3 /Gy
                   12331:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12332:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12333:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12334:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12335:    */ 
                   12336:    /* 64 bits */
1.185     brouard  12337:    /*
                   12338:      /GS /W3 /Gy
                   12339:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12340:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12341:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12342:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12343:    /* Optimization are useless and O3 is slower than O2 */
                   12344:    /*
                   12345:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12346:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12347:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12348:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12349:    */
1.186     brouard  12350:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12351:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12352:       /PDB:"visual studio
                   12353:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12354:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12355:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12356:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12357:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12358:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12359:       uiAccess='false'"
                   12360:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12361:       /NOLOGO /TLBID:1
                   12362:    */
1.292     brouard  12363: 
                   12364: 
1.177     brouard  12365: #if defined __INTEL_COMPILER
1.178     brouard  12366: #if defined(__GNUC__)
                   12367:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12368: #endif
1.177     brouard  12369: #elif defined(__GNUC__) 
1.179     brouard  12370: #ifndef  __APPLE__
1.174     brouard  12371: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12372: #endif
1.177     brouard  12373:    struct utsname sysInfo;
1.178     brouard  12374:    int cross = CROSS;
                   12375:    if (cross){
                   12376:           printf("Cross-");
1.191     brouard  12377:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12378:    }
1.174     brouard  12379: #endif
                   12380: 
1.191     brouard  12381:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12382: #if defined(__clang__)
1.191     brouard  12383:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12384: #endif
                   12385: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12386:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12387: #endif
                   12388: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12389:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12390: #endif
                   12391: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12392:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12393: #endif
                   12394: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12395:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12396: #endif
                   12397: #if defined(_MSC_VER)
1.191     brouard  12398:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12399: #endif
                   12400: #if defined(__PGI)
1.191     brouard  12401:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12402: #endif
                   12403: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12404:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12405: #endif
1.191     brouard  12406:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12407:    
1.167     brouard  12408: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12409: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12410:     // Windows (x64 and x86)
1.191     brouard  12411:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12412: #elif __unix__ // all unices, not all compilers
                   12413:     // Unix
1.191     brouard  12414:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12415: #elif __linux__
                   12416:     // linux
1.191     brouard  12417:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12418: #elif __APPLE__
1.174     brouard  12419:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12420:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12421: #endif
                   12422: 
                   12423: /*  __MINGW32__          */
                   12424: /*  __CYGWIN__  */
                   12425: /* __MINGW64__  */
                   12426: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12427: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12428: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12429: /* _WIN64  // Defined for applications for Win64. */
                   12430: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12431: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12432: 
1.167     brouard  12433: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12434:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12435: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12436:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12437: #else
1.191     brouard  12438:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12439: #endif
                   12440: 
1.169     brouard  12441: #if defined(__GNUC__)
                   12442: # if defined(__GNUC_PATCHLEVEL__)
                   12443: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12444:                             + __GNUC_MINOR__ * 100 \
                   12445:                             + __GNUC_PATCHLEVEL__)
                   12446: # else
                   12447: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12448:                             + __GNUC_MINOR__ * 100)
                   12449: # endif
1.174     brouard  12450:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12451:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12452: 
                   12453:    if (uname(&sysInfo) != -1) {
                   12454:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12455:         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  12456:    }
                   12457:    else
                   12458:       perror("uname() error");
1.179     brouard  12459:    //#ifndef __INTEL_COMPILER 
                   12460: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12461:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12462:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12463: #endif
1.169     brouard  12464: #endif
1.172     brouard  12465: 
1.286     brouard  12466:    //   void main ()
1.172     brouard  12467:    //   {
1.169     brouard  12468: #if defined(_MSC_VER)
1.174     brouard  12469:    if (IsWow64()){
1.191     brouard  12470:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12471:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12472:    }
                   12473:    else{
1.191     brouard  12474:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12475:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12476:    }
1.172     brouard  12477:    //     printf("\nPress Enter to continue...");
                   12478:    //     getchar();
                   12479:    //   }
                   12480: 
1.169     brouard  12481: #endif
                   12482:    
1.167     brouard  12483: 
1.219     brouard  12484: }
1.136     brouard  12485: 
1.219     brouard  12486: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12487:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12488:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12489:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12490:   /* double ftolpl = 1.e-10; */
1.180     brouard  12491:   double age, agebase, agelim;
1.203     brouard  12492:   double tot;
1.180     brouard  12493: 
1.202     brouard  12494:   strcpy(filerespl,"PL_");
                   12495:   strcat(filerespl,fileresu);
                   12496:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12497:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12498:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12499:   }
1.288     brouard  12500:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12501:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12502:   pstamp(ficrespl);
1.288     brouard  12503:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12504:   fprintf(ficrespl,"#Age ");
                   12505:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12506:   fprintf(ficrespl,"\n");
1.180     brouard  12507:   
1.219     brouard  12508:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12509: 
1.219     brouard  12510:   agebase=ageminpar;
                   12511:   agelim=agemaxpar;
1.180     brouard  12512: 
1.227     brouard  12513:   /* i1=pow(2,ncoveff); */
1.234     brouard  12514:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12515:   if (cptcovn < 1){i1=1;}
1.180     brouard  12516: 
1.337     brouard  12517:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12518:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12519:       k=TKresult[nres];
1.338     brouard  12520:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12521:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12522:       /*       continue; */
1.235     brouard  12523: 
1.238     brouard  12524:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12525:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12526:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12527:       /* k=k+1; */
                   12528:       /* to clean */
1.332     brouard  12529:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12530:       fprintf(ficrespl,"#******");
                   12531:       printf("#******");
                   12532:       fprintf(ficlog,"#******");
1.337     brouard  12533:       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  12534:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12535:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12536:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12537:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12538:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12539:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12540:       }
                   12541:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12542:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12543:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12544:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12545:       /* } */
1.238     brouard  12546:       fprintf(ficrespl,"******\n");
                   12547:       printf("******\n");
                   12548:       fprintf(ficlog,"******\n");
                   12549:       if(invalidvarcomb[k]){
                   12550:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12551:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12552:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12553:        continue;
                   12554:       }
1.219     brouard  12555: 
1.238     brouard  12556:       fprintf(ficrespl,"#Age ");
1.337     brouard  12557:       /* for(j=1;j<=cptcoveff;j++) { */
                   12558:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12559:       /* } */
                   12560:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12561:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12562:       }
                   12563:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12564:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12565:     
1.238     brouard  12566:       for (age=agebase; age<=agelim; age++){
                   12567:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12568:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12569:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12570:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12571:        /* for(j=1;j<=cptcoveff;j++) */
                   12572:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12573:        for(j=1;j<=cptcovs;j++)
                   12574:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12575:        tot=0.;
                   12576:        for(i=1; i<=nlstate;i++){
                   12577:          tot +=  prlim[i][i];
                   12578:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12579:        }
                   12580:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12581:       } /* Age */
                   12582:       /* was end of cptcod */
1.337     brouard  12583:     } /* nres */
                   12584:   /* } /\* for each combination *\/ */
1.219     brouard  12585:   return 0;
1.180     brouard  12586: }
                   12587: 
1.218     brouard  12588: 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  12589:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12590:        
                   12591:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12592:    * at any age between ageminpar and agemaxpar
                   12593:         */
1.235     brouard  12594:   int i, j, k, i1, nres=0 ;
1.217     brouard  12595:   /* double ftolpl = 1.e-10; */
                   12596:   double age, agebase, agelim;
                   12597:   double tot;
1.218     brouard  12598:   /* double ***mobaverage; */
                   12599:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12600: 
                   12601:   strcpy(fileresplb,"PLB_");
                   12602:   strcat(fileresplb,fileresu);
                   12603:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12604:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12605:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12606:   }
1.288     brouard  12607:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12608:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12609:   pstamp(ficresplb);
1.288     brouard  12610:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12611:   fprintf(ficresplb,"#Age ");
                   12612:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12613:   fprintf(ficresplb,"\n");
                   12614:   
1.218     brouard  12615:   
                   12616:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12617:   
                   12618:   agebase=ageminpar;
                   12619:   agelim=agemaxpar;
                   12620:   
                   12621:   
1.227     brouard  12622:   i1=pow(2,cptcoveff);
1.218     brouard  12623:   if (cptcovn < 1){i1=1;}
1.227     brouard  12624:   
1.238     brouard  12625:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12626:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12627:       k=TKresult[nres];
                   12628:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12629:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12630:      /*        continue; */
                   12631:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12632:       fprintf(ficresplb,"#******");
                   12633:       printf("#******");
                   12634:       fprintf(ficlog,"#******");
1.338     brouard  12635:       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) */
                   12636:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12637:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12638:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12639:       }
1.338     brouard  12640:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12641:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12642:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12643:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12644:       /* } */
                   12645:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12646:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12647:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12648:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12649:       /* } */
1.238     brouard  12650:       fprintf(ficresplb,"******\n");
                   12651:       printf("******\n");
                   12652:       fprintf(ficlog,"******\n");
                   12653:       if(invalidvarcomb[k]){
                   12654:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12655:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12656:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12657:        continue;
                   12658:       }
1.218     brouard  12659:     
1.238     brouard  12660:       fprintf(ficresplb,"#Age ");
1.338     brouard  12661:       for(j=1;j<=cptcovs;j++) {
                   12662:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12663:       }
                   12664:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12665:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12666:     
                   12667:     
1.238     brouard  12668:       for (age=agebase; age<=agelim; age++){
                   12669:        /* for (age=agebase; age<=agebase; age++){ */
                   12670:        if(mobilavproj > 0){
                   12671:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12672:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12673:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12674:        }else if (mobilavproj == 0){
                   12675:          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);
                   12676:          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);
                   12677:          exit(1);
                   12678:        }else{
                   12679:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12680:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12681:          /* printf("TOTOT\n"); */
                   12682:           /* exit(1); */
1.238     brouard  12683:        }
                   12684:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12685:        for(j=1;j<=cptcovs;j++)
                   12686:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12687:        tot=0.;
                   12688:        for(i=1; i<=nlstate;i++){
                   12689:          tot +=  bprlim[i][i];
                   12690:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12691:        }
                   12692:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12693:       } /* Age */
                   12694:       /* was end of cptcod */
1.255     brouard  12695:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12696:     /* } /\* end of any combination *\/ */
1.238     brouard  12697:   } /* end of nres */  
1.218     brouard  12698:   /* hBijx(p, bage, fage); */
                   12699:   /* fclose(ficrespijb); */
                   12700:   
                   12701:   return 0;
1.217     brouard  12702: }
1.218     brouard  12703:  
1.180     brouard  12704: int hPijx(double *p, int bage, int fage){
                   12705:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12706:   /* to be optimized with precov */
1.180     brouard  12707:   int stepsize;
                   12708:   int agelim;
                   12709:   int hstepm;
                   12710:   int nhstepm;
1.235     brouard  12711:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12712: 
                   12713:   double agedeb;
                   12714:   double ***p3mat;
                   12715: 
1.337     brouard  12716:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12717:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12718:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12719:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12720:   }
                   12721:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12722:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12723:   
                   12724:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12725:   /*if (stepm<=24) stepsize=2;*/
                   12726:   
                   12727:   agelim=AGESUP;
                   12728:   hstepm=stepsize*YEARM; /* Every year of age */
                   12729:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12730:   
                   12731:   /* hstepm=1;   aff par mois*/
                   12732:   pstamp(ficrespij);
                   12733:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12734:   i1= pow(2,cptcoveff);
                   12735:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12736:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12737:   /*   k=k+1;  */
                   12738:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12739:     k=TKresult[nres];
1.338     brouard  12740:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12741:     /* for(k=1; k<=i1;k++){ */
                   12742:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12743:     /*         continue; */
                   12744:     fprintf(ficrespij,"\n#****** ");
                   12745:     for(j=1;j<=cptcovs;j++){
                   12746:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12747:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12748:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12749:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12750:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12751:     }
                   12752:     fprintf(ficrespij,"******\n");
                   12753:     
                   12754:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12755:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12756:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12757:       
                   12758:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12759:       
                   12760:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12761:       oldm=oldms;savm=savms;
                   12762:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12763:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12764:       for(i=1; i<=nlstate;i++)
                   12765:        for(j=1; j<=nlstate+ndeath;j++)
                   12766:          fprintf(ficrespij," %1d-%1d",i,j);
                   12767:       fprintf(ficrespij,"\n");
                   12768:       for (h=0; h<=nhstepm; h++){
                   12769:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12770:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12771:        for(i=1; i<=nlstate;i++)
                   12772:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12773:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12774:        fprintf(ficrespij,"\n");
                   12775:       }
1.337     brouard  12776:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12777:       fprintf(ficrespij,"\n");
1.180     brouard  12778:     }
1.337     brouard  12779:   }
                   12780:   /*}*/
                   12781:   return 0;
1.180     brouard  12782: }
1.218     brouard  12783:  
                   12784:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12785:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12786:     /* To be optimized with precov */
1.217     brouard  12787:   int stepsize;
1.218     brouard  12788:   /* int agelim; */
                   12789:        int ageminl;
1.217     brouard  12790:   int hstepm;
                   12791:   int nhstepm;
1.238     brouard  12792:   int h, i, i1, j, k, nres;
1.218     brouard  12793:        
1.217     brouard  12794:   double agedeb;
                   12795:   double ***p3mat;
1.218     brouard  12796:        
                   12797:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12798:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12799:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12800:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12801:   }
                   12802:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12803:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12804:   
                   12805:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12806:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12807:   
1.218     brouard  12808:   /* agelim=AGESUP; */
1.289     brouard  12809:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12810:   hstepm=stepsize*YEARM; /* Every year of age */
                   12811:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12812:   
                   12813:   /* hstepm=1;   aff par mois*/
                   12814:   pstamp(ficrespijb);
1.255     brouard  12815:   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  12816:   i1= pow(2,cptcoveff);
1.218     brouard  12817:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12818:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12819:   /*   k=k+1;  */
1.238     brouard  12820:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12821:     k=TKresult[nres];
1.338     brouard  12822:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12823:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12824:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12825:     /*         continue; */
                   12826:     fprintf(ficrespijb,"\n#****** ");
                   12827:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12828:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12829:       /* for(j=1;j<=cptcoveff;j++) */
                   12830:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12831:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12832:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12833:     }
                   12834:     fprintf(ficrespijb,"******\n");
                   12835:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12836:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12837:       continue;
                   12838:     }
                   12839:     
                   12840:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12841:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12842:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12843:       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 */
                   12844:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12845:       
                   12846:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12847:       
                   12848:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12849:       /* and memory limitations if stepm is small */
                   12850:       
                   12851:       /* oldm=oldms;savm=savms; */
                   12852:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12853:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12854:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12855:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12856:       for(i=1; i<=nlstate;i++)
                   12857:        for(j=1; j<=nlstate+ndeath;j++)
                   12858:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12859:       fprintf(ficrespijb,"\n");
                   12860:       for (h=0; h<=nhstepm; h++){
                   12861:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12862:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12863:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12864:        for(i=1; i<=nlstate;i++)
                   12865:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12866:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12867:        fprintf(ficrespijb,"\n");
1.337     brouard  12868:       }
                   12869:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12870:       fprintf(ficrespijb,"\n");
                   12871:     } /* end age deb */
                   12872:     /* } /\* end combination *\/ */
1.238     brouard  12873:   } /* end nres */
1.218     brouard  12874:   return 0;
                   12875:  } /*  hBijx */
1.217     brouard  12876: 
1.180     brouard  12877: 
1.136     brouard  12878: /***********************************************/
                   12879: /**************** Main Program *****************/
                   12880: /***********************************************/
                   12881: 
                   12882: int main(int argc, char *argv[])
                   12883: {
                   12884: #ifdef GSL
                   12885:   const gsl_multimin_fminimizer_type *T;
                   12886:   size_t iteri = 0, it;
                   12887:   int rval = GSL_CONTINUE;
                   12888:   int status = GSL_SUCCESS;
                   12889:   double ssval;
                   12890: #endif
                   12891:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12892:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12893:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12894:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12895:   int jj, ll, li, lj, lk;
1.136     brouard  12896:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12897:   int num_filled;
1.136     brouard  12898:   int itimes;
                   12899:   int NDIM=2;
                   12900:   int vpopbased=0;
1.235     brouard  12901:   int nres=0;
1.258     brouard  12902:   int endishere=0;
1.277     brouard  12903:   int noffset=0;
1.274     brouard  12904:   int ncurrv=0; /* Temporary variable */
                   12905:   
1.164     brouard  12906:   char ca[32], cb[32];
1.136     brouard  12907:   /*  FILE *fichtm; *//* Html File */
                   12908:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12909:   struct stat info;
1.191     brouard  12910:   double agedeb=0.;
1.194     brouard  12911: 
                   12912:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12913:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12914: 
1.165     brouard  12915:   double fret;
1.191     brouard  12916:   double dum=0.; /* Dummy variable */
1.136     brouard  12917:   double ***p3mat;
1.218     brouard  12918:   /* double ***mobaverage; */
1.319     brouard  12919:   double wald;
1.164     brouard  12920: 
                   12921:   char line[MAXLINE];
1.197     brouard  12922:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12923: 
1.234     brouard  12924:   char  modeltemp[MAXLINE];
1.332     brouard  12925:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12926:   
1.136     brouard  12927:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12928:   char *tok, *val; /* pathtot */
1.334     brouard  12929:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12930:   int c,  h , cpt, c2;
1.191     brouard  12931:   int jl=0;
                   12932:   int i1, j1, jk, stepsize=0;
1.194     brouard  12933:   int count=0;
                   12934: 
1.164     brouard  12935:   int *tab; 
1.136     brouard  12936:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12937:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12938:   /* double anprojf, mprojf, jprojf; */
                   12939:   /* double jintmean,mintmean,aintmean;   */
                   12940:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12941:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12942:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12943:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12944:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12945:   int mobilav=0,popforecast=0;
1.191     brouard  12946:   int hstepm=0, nhstepm=0;
1.136     brouard  12947:   int agemortsup;
                   12948:   float  sumlpop=0.;
                   12949:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12950:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12951: 
1.191     brouard  12952:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12953:   double ftolpl=FTOL;
                   12954:   double **prlim;
1.217     brouard  12955:   double **bprlim;
1.317     brouard  12956:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12957:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12958:   double ***paramstart; /* Matrix of starting parameter values */
                   12959:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12960:   double **matcov; /* Matrix of covariance */
1.203     brouard  12961:   double **hess; /* Hessian matrix */
1.136     brouard  12962:   double ***delti3; /* Scale */
                   12963:   double *delti; /* Scale */
                   12964:   double ***eij, ***vareij;
                   12965:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12966: 
1.136     brouard  12967:   double *epj, vepp;
1.164     brouard  12968: 
1.273     brouard  12969:   double dateprev1, dateprev2;
1.296     brouard  12970:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12971:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12972: 
1.217     brouard  12973: 
1.136     brouard  12974:   double **ximort;
1.145     brouard  12975:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12976:   int *dcwave;
                   12977: 
1.164     brouard  12978:   char z[1]="c";
1.136     brouard  12979: 
                   12980:   /*char  *strt;*/
                   12981:   char strtend[80];
1.126     brouard  12982: 
1.164     brouard  12983: 
1.126     brouard  12984: /*   setlocale (LC_ALL, ""); */
                   12985: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12986: /*   textdomain (PACKAGE); */
                   12987: /*   setlocale (LC_CTYPE, ""); */
                   12988: /*   setlocale (LC_MESSAGES, ""); */
                   12989: 
                   12990:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12991:   rstart_time = time(NULL);  
                   12992:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12993:   start_time = *localtime(&rstart_time);
1.126     brouard  12994:   curr_time=start_time;
1.157     brouard  12995:   /*tml = *localtime(&start_time.tm_sec);*/
                   12996:   /* strcpy(strstart,asctime(&tml)); */
                   12997:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12998: 
                   12999: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13000: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13001: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13002: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13003: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13004: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13005: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13006: /*   strt=asctime(&tmg); */
                   13007: /*   printf("Time(after) =%s",strstart);  */
                   13008: /*  (void) time (&time_value);
                   13009: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13010: *  tm = *localtime(&time_value);
                   13011: *  strstart=asctime(&tm);
                   13012: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13013: */
                   13014: 
                   13015:   nberr=0; /* Number of errors and warnings */
                   13016:   nbwarn=0;
1.184     brouard  13017: #ifdef WIN32
                   13018:   _getcwd(pathcd, size);
                   13019: #else
1.126     brouard  13020:   getcwd(pathcd, size);
1.184     brouard  13021: #endif
1.191     brouard  13022:   syscompilerinfo(0);
1.196     brouard  13023:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13024:   if(argc <=1){
                   13025:     printf("\nEnter the parameter file name: ");
1.205     brouard  13026:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13027:       printf("ERROR Empty parameter file name\n");
                   13028:       goto end;
                   13029:     }
1.126     brouard  13030:     i=strlen(pathr);
                   13031:     if(pathr[i-1]=='\n')
                   13032:       pathr[i-1]='\0';
1.156     brouard  13033:     i=strlen(pathr);
1.205     brouard  13034:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13035:       pathr[i-1]='\0';
1.205     brouard  13036:     }
                   13037:     i=strlen(pathr);
                   13038:     if( i==0 ){
                   13039:       printf("ERROR Empty parameter file name\n");
                   13040:       goto end;
                   13041:     }
                   13042:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13043:       printf("Pathr |%s|\n",pathr);
                   13044:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13045:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13046:       strcpy (pathtot, val);
                   13047:       if(pathr[0] == '\0') break; /* Dirty */
                   13048:     }
                   13049:   }
1.281     brouard  13050:   else if (argc<=2){
                   13051:     strcpy(pathtot,argv[1]);
                   13052:   }
1.126     brouard  13053:   else{
                   13054:     strcpy(pathtot,argv[1]);
1.281     brouard  13055:     strcpy(z,argv[2]);
                   13056:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13057:   }
                   13058:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13059:   /*cygwin_split_path(pathtot,path,optionfile);
                   13060:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13061:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13062: 
                   13063:   /* Split argv[0], imach program to get pathimach */
                   13064:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13065:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13066:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13067:  /*   strcpy(pathimach,argv[0]); */
                   13068:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13069:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13070:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13071: #ifdef WIN32
                   13072:   _chdir(path); /* Can be a relative path */
                   13073:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13074: #else
1.126     brouard  13075:   chdir(path); /* Can be a relative path */
1.184     brouard  13076:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13077: #endif
                   13078:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13079:   strcpy(command,"mkdir ");
                   13080:   strcat(command,optionfilefiname);
                   13081:   if((outcmd=system(command)) != 0){
1.169     brouard  13082:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13083:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13084:     /* fclose(ficlog); */
                   13085: /*     exit(1); */
                   13086:   }
                   13087: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13088: /*     perror("mkdir"); */
                   13089: /*   } */
                   13090: 
                   13091:   /*-------- arguments in the command line --------*/
                   13092: 
1.186     brouard  13093:   /* Main Log file */
1.126     brouard  13094:   strcat(filelog, optionfilefiname);
                   13095:   strcat(filelog,".log");    /* */
                   13096:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13097:     printf("Problem with logfile %s\n",filelog);
                   13098:     goto end;
                   13099:   }
                   13100:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13101:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13102:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13103:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13104:  path=%s \n\
                   13105:  optionfile=%s\n\
                   13106:  optionfilext=%s\n\
1.156     brouard  13107:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13108: 
1.197     brouard  13109:   syscompilerinfo(1);
1.167     brouard  13110: 
1.126     brouard  13111:   printf("Local time (at start):%s",strstart);
                   13112:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13113:   fflush(ficlog);
                   13114: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13115: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13116: 
                   13117:   /* */
                   13118:   strcpy(fileres,"r");
                   13119:   strcat(fileres, optionfilefiname);
1.201     brouard  13120:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13121:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13122:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13123: 
1.186     brouard  13124:   /* Main ---------arguments file --------*/
1.126     brouard  13125: 
                   13126:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13127:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13128:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13129:     fflush(ficlog);
1.149     brouard  13130:     /* goto end; */
                   13131:     exit(70); 
1.126     brouard  13132:   }
                   13133: 
                   13134:   strcpy(filereso,"o");
1.201     brouard  13135:   strcat(filereso,fileresu);
1.126     brouard  13136:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13137:     printf("Problem with Output resultfile: %s\n", filereso);
                   13138:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13139:     fflush(ficlog);
                   13140:     goto end;
                   13141:   }
1.278     brouard  13142:       /*-------- Rewriting parameter file ----------*/
                   13143:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13144:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13145:   strcat(rfileres,".");    /* */
                   13146:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13147:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13148:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13149:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13150:     fflush(ficlog);
                   13151:     goto end;
                   13152:   }
                   13153:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13154: 
1.278     brouard  13155:                                      
1.126     brouard  13156:   /* Reads comments: lines beginning with '#' */
                   13157:   numlinepar=0;
1.277     brouard  13158:   /* Is it a BOM UTF-8 Windows file? */
                   13159:   /* First parameter line */
1.197     brouard  13160:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13161:     noffset=0;
                   13162:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13163:     {
                   13164:       noffset=noffset+3;
                   13165:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13166:     }
1.302     brouard  13167: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13168:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13169:     {
                   13170:       noffset=noffset+2;
                   13171:       printf("# File is an UTF16BE BOM file\n");
                   13172:     }
                   13173:     else if( line[0] == 0 && line[1] == 0)
                   13174:     {
                   13175:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13176:        noffset=noffset+4;
                   13177:        printf("# File is an UTF16BE BOM file\n");
                   13178:       }
                   13179:     } else{
                   13180:       ;/*printf(" Not a BOM file\n");*/
                   13181:     }
                   13182:   
1.197     brouard  13183:     /* If line starts with a # it is a comment */
1.277     brouard  13184:     if (line[noffset] == '#') {
1.197     brouard  13185:       numlinepar++;
                   13186:       fputs(line,stdout);
                   13187:       fputs(line,ficparo);
1.278     brouard  13188:       fputs(line,ficres);
1.197     brouard  13189:       fputs(line,ficlog);
                   13190:       continue;
                   13191:     }else
                   13192:       break;
                   13193:   }
                   13194:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13195:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13196:     if (num_filled != 5) {
                   13197:       printf("Should be 5 parameters\n");
1.283     brouard  13198:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13199:     }
1.126     brouard  13200:     numlinepar++;
1.197     brouard  13201:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13202:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13203:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13204:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13205:   }
                   13206:   /* Second parameter line */
                   13207:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13208:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13209:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13210:     if (line[0] == '#') {
                   13211:       numlinepar++;
1.283     brouard  13212:       printf("%s",line);
                   13213:       fprintf(ficres,"%s",line);
                   13214:       fprintf(ficparo,"%s",line);
                   13215:       fprintf(ficlog,"%s",line);
1.197     brouard  13216:       continue;
                   13217:     }else
                   13218:       break;
                   13219:   }
1.223     brouard  13220:   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", \
                   13221:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13222:     if (num_filled != 11) {
                   13223:       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  13224:       printf("but line=%s\n",line);
1.283     brouard  13225:       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");
                   13226:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13227:     }
1.286     brouard  13228:     if( lastpass > maxwav){
                   13229:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13230:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13231:       fflush(ficlog);
                   13232:       goto end;
                   13233:     }
                   13234:       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  13235:     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  13236:     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  13237:     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  13238:   }
1.203     brouard  13239:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13240:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13241:   /* Third parameter line */
                   13242:   while(fgets(line, MAXLINE, ficpar)) {
                   13243:     /* If line starts with a # it is a comment */
                   13244:     if (line[0] == '#') {
                   13245:       numlinepar++;
1.283     brouard  13246:       printf("%s",line);
                   13247:       fprintf(ficres,"%s",line);
                   13248:       fprintf(ficparo,"%s",line);
                   13249:       fprintf(ficlog,"%s",line);
1.197     brouard  13250:       continue;
                   13251:     }else
                   13252:       break;
                   13253:   }
1.201     brouard  13254:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  13255:     if (num_filled != 1){
1.302     brouard  13256:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13257:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13258:       model[0]='\0';
                   13259:       goto end;
                   13260:     }
                   13261:     else{
                   13262:       if (model[0]=='+'){
                   13263:        for(i=1; i<=strlen(model);i++)
                   13264:          modeltemp[i-1]=model[i];
1.201     brouard  13265:        strcpy(model,modeltemp); 
1.197     brouard  13266:       }
                   13267:     }
1.338     brouard  13268:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13269:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13270:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13271:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13272:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13273:   }
                   13274:   /* 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); */
                   13275:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13276:   /* 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  13277:   /* 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); */
                   13278:   /* 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  13279:   fflush(ficlog);
1.190     brouard  13280:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13281:   if(model[0]=='#'){
1.279     brouard  13282:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13283:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13284:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13285:     if(mle != -1){
1.279     brouard  13286:       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  13287:       exit(1);
                   13288:     }
                   13289:   }
1.126     brouard  13290:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13291:     ungetc(c,ficpar);
                   13292:     fgets(line, MAXLINE, ficpar);
                   13293:     numlinepar++;
1.195     brouard  13294:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13295:       z[0]=line[1];
1.342     brouard  13296:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13297:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13298:     }
                   13299:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13300:     fputs(line, stdout);
                   13301:     //puts(line);
1.126     brouard  13302:     fputs(line,ficparo);
                   13303:     fputs(line,ficlog);
                   13304:   }
                   13305:   ungetc(c,ficpar);
                   13306: 
                   13307:    
1.290     brouard  13308:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13309:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13310:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13311:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13312:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13313:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13314:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13315:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13316:   */
                   13317:   if (strlen(model)>1) 
1.187     brouard  13318:     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  13319:   else
1.187     brouard  13320:     ncovmodel=2; /* Constant and age */
1.133     brouard  13321:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13322:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13323:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13324:     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);
                   13325:     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);
                   13326:     fflush(stdout);
                   13327:     fclose (ficlog);
                   13328:     goto end;
                   13329:   }
1.126     brouard  13330:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13331:   delti=delti3[1][1];
                   13332:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13333:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13334: /* We could also provide initial parameters values giving by simple logistic regression 
                   13335:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13336:       /* for(i=1;i<nlstate;i++){ */
                   13337:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13338:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13339:       /* } */
1.126     brouard  13340:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13341:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13342:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13343:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13344:     fclose (ficparo);
                   13345:     fclose (ficlog);
                   13346:     goto end;
                   13347:     exit(0);
1.220     brouard  13348:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13349:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13350:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13351:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13352:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13353:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13354:     hess=matrix(1,npar,1,npar);
1.220     brouard  13355:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13356:     /* Read guessed parameters */
1.126     brouard  13357:     /* Reads comments: lines beginning with '#' */
                   13358:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13359:       ungetc(c,ficpar);
                   13360:       fgets(line, MAXLINE, ficpar);
                   13361:       numlinepar++;
1.141     brouard  13362:       fputs(line,stdout);
1.126     brouard  13363:       fputs(line,ficparo);
                   13364:       fputs(line,ficlog);
                   13365:     }
                   13366:     ungetc(c,ficpar);
                   13367:     
                   13368:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13369:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13370:     for(i=1; i <=nlstate; i++){
1.234     brouard  13371:       j=0;
1.126     brouard  13372:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13373:        if(jj==i) continue;
                   13374:        j++;
1.292     brouard  13375:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13376:          ungetc(c,ficpar);
                   13377:          fgets(line, MAXLINE, ficpar);
                   13378:          numlinepar++;
                   13379:          fputs(line,stdout);
                   13380:          fputs(line,ficparo);
                   13381:          fputs(line,ficlog);
                   13382:        }
                   13383:        ungetc(c,ficpar);
1.234     brouard  13384:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13385:        if ((i1 != i) || (j1 != jj)){
                   13386:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13387: It might be a problem of design; if ncovcol and the model are correct\n \
                   13388: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13389:          exit(1);
                   13390:        }
                   13391:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13392:        if(mle==1)
                   13393:          printf("%1d%1d",i,jj);
                   13394:        fprintf(ficlog,"%1d%1d",i,jj);
                   13395:        for(k=1; k<=ncovmodel;k++){
                   13396:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13397:          if(mle==1){
                   13398:            printf(" %lf",param[i][j][k]);
                   13399:            fprintf(ficlog," %lf",param[i][j][k]);
                   13400:          }
                   13401:          else
                   13402:            fprintf(ficlog," %lf",param[i][j][k]);
                   13403:          fprintf(ficparo," %lf",param[i][j][k]);
                   13404:        }
                   13405:        fscanf(ficpar,"\n");
                   13406:        numlinepar++;
                   13407:        if(mle==1)
                   13408:          printf("\n");
                   13409:        fprintf(ficlog,"\n");
                   13410:        fprintf(ficparo,"\n");
1.126     brouard  13411:       }
                   13412:     }  
                   13413:     fflush(ficlog);
1.234     brouard  13414:     
1.251     brouard  13415:     /* Reads parameters values */
1.126     brouard  13416:     p=param[1][1];
1.251     brouard  13417:     pstart=paramstart[1][1];
1.126     brouard  13418:     
                   13419:     /* Reads comments: lines beginning with '#' */
                   13420:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13421:       ungetc(c,ficpar);
                   13422:       fgets(line, MAXLINE, ficpar);
                   13423:       numlinepar++;
1.141     brouard  13424:       fputs(line,stdout);
1.126     brouard  13425:       fputs(line,ficparo);
                   13426:       fputs(line,ficlog);
                   13427:     }
                   13428:     ungetc(c,ficpar);
                   13429: 
                   13430:     for(i=1; i <=nlstate; i++){
                   13431:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13432:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13433:        if ( (i1-i) * (j1-j) != 0){
                   13434:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13435:          exit(1);
                   13436:        }
                   13437:        printf("%1d%1d",i,j);
                   13438:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13439:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13440:        for(k=1; k<=ncovmodel;k++){
                   13441:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13442:          printf(" %le",delti3[i][j][k]);
                   13443:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13444:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13445:        }
                   13446:        fscanf(ficpar,"\n");
                   13447:        numlinepar++;
                   13448:        printf("\n");
                   13449:        fprintf(ficparo,"\n");
                   13450:        fprintf(ficlog,"\n");
1.126     brouard  13451:       }
                   13452:     }
                   13453:     fflush(ficlog);
1.234     brouard  13454:     
1.145     brouard  13455:     /* Reads covariance matrix */
1.126     brouard  13456:     delti=delti3[1][1];
1.220     brouard  13457:                
                   13458:                
1.126     brouard  13459:     /* 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  13460:                
1.126     brouard  13461:     /* Reads comments: lines beginning with '#' */
                   13462:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13463:       ungetc(c,ficpar);
                   13464:       fgets(line, MAXLINE, ficpar);
                   13465:       numlinepar++;
1.141     brouard  13466:       fputs(line,stdout);
1.126     brouard  13467:       fputs(line,ficparo);
                   13468:       fputs(line,ficlog);
                   13469:     }
                   13470:     ungetc(c,ficpar);
1.220     brouard  13471:                
1.126     brouard  13472:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13473:     hess=matrix(1,npar,1,npar);
1.131     brouard  13474:     for(i=1; i <=npar; i++)
                   13475:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13476:                
1.194     brouard  13477:     /* Scans npar lines */
1.126     brouard  13478:     for(i=1; i <=npar; i++){
1.226     brouard  13479:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13480:       if(count != 3){
1.226     brouard  13481:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13482: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13483: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13484:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13485: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13486: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13487:        exit(1);
1.220     brouard  13488:       }else{
1.226     brouard  13489:        if(mle==1)
                   13490:          printf("%1d%1d%d",i1,j1,jk);
                   13491:       }
                   13492:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13493:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13494:       for(j=1; j <=i; j++){
1.226     brouard  13495:        fscanf(ficpar," %le",&matcov[i][j]);
                   13496:        if(mle==1){
                   13497:          printf(" %.5le",matcov[i][j]);
                   13498:        }
                   13499:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13500:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13501:       }
                   13502:       fscanf(ficpar,"\n");
                   13503:       numlinepar++;
                   13504:       if(mle==1)
1.220     brouard  13505:                                printf("\n");
1.126     brouard  13506:       fprintf(ficlog,"\n");
                   13507:       fprintf(ficparo,"\n");
                   13508:     }
1.194     brouard  13509:     /* End of read covariance matrix npar lines */
1.126     brouard  13510:     for(i=1; i <=npar; i++)
                   13511:       for(j=i+1;j<=npar;j++)
1.226     brouard  13512:        matcov[i][j]=matcov[j][i];
1.126     brouard  13513:     
                   13514:     if(mle==1)
                   13515:       printf("\n");
                   13516:     fprintf(ficlog,"\n");
                   13517:     
                   13518:     fflush(ficlog);
                   13519:     
                   13520:   }    /* End of mle != -3 */
1.218     brouard  13521:   
1.186     brouard  13522:   /*  Main data
                   13523:    */
1.290     brouard  13524:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13525:   /* num=lvector(1,n); */
                   13526:   /* moisnais=vector(1,n); */
                   13527:   /* annais=vector(1,n); */
                   13528:   /* moisdc=vector(1,n); */
                   13529:   /* andc=vector(1,n); */
                   13530:   /* weight=vector(1,n); */
                   13531:   /* agedc=vector(1,n); */
                   13532:   /* cod=ivector(1,n); */
                   13533:   /* for(i=1;i<=n;i++){ */
                   13534:   num=lvector(firstobs,lastobs);
                   13535:   moisnais=vector(firstobs,lastobs);
                   13536:   annais=vector(firstobs,lastobs);
                   13537:   moisdc=vector(firstobs,lastobs);
                   13538:   andc=vector(firstobs,lastobs);
                   13539:   weight=vector(firstobs,lastobs);
                   13540:   agedc=vector(firstobs,lastobs);
                   13541:   cod=ivector(firstobs,lastobs);
                   13542:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13543:     num[i]=0;
                   13544:     moisnais[i]=0;
                   13545:     annais[i]=0;
                   13546:     moisdc[i]=0;
                   13547:     andc[i]=0;
                   13548:     agedc[i]=0;
                   13549:     cod[i]=0;
                   13550:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13551:   }
1.290     brouard  13552:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13553:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13554:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13555:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13556:   tab=ivector(1,NCOVMAX);
1.144     brouard  13557:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13558:   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  13559: 
1.136     brouard  13560:   /* Reads data from file datafile */
                   13561:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13562:     goto end;
                   13563: 
                   13564:   /* Calculation of the number of parameters from char model */
1.234     brouard  13565:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13566:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13567:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13568:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13569:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13570:   */
                   13571:   
                   13572:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13573:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13574:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13575:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13576:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13577:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13578:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13579:   TvarF=ivector(1,NCOVMAX); /*  */
                   13580:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13581:   TvarV=ivector(1,NCOVMAX); /*  */
                   13582:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13583:   TvarA=ivector(1,NCOVMAX); /*  */
                   13584:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13585:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13586:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13587:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13588:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13589:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13590:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13591:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13592:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13593:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13594:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349   ! brouard  13595:   TvarVVA=ivector(1,NCOVMAX); /*  */
        !          13596:   TvarVVAind=ivector(1,NCOVMAX); /*  */
        !          13597:   TvarAVVA=ivector(1,NCOVMAX); /*  */
        !          13598:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13599: 
1.230     brouard  13600:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13601:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13602:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13603:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13604:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349   ! brouard  13605:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
        !          13606:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
        !          13607: 
1.137     brouard  13608:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13609:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13610:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13611:   */
                   13612:   /* For model-covariate k tells which data-covariate to use but
                   13613:     because this model-covariate is a construction we invent a new column
                   13614:     ncovcol + k1
                   13615:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13616:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13617:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13618:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13619:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13620:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13621:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13622:   */
1.145     brouard  13623:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13624:   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  13625:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13626:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.349   ! brouard  13627:   Tvardk=imatrix(-1,NCOVMAX,1,2);
1.145     brouard  13628:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13629:                         4 covariates (3 plus signs)
                   13630:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13631:                           */  
                   13632:   for(i=1;i<NCOVMAX;i++)
                   13633:     Tage[i]=0;
1.230     brouard  13634:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13635:                                * individual dummy, fixed or varying:
                   13636:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13637:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13638:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13639:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13640:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13641:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13642:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13643:                                * individual quantitative, fixed or varying:
                   13644:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13645:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13646:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349   ! brouard  13647: 
        !          13648: /* Probably useless zeroes */
        !          13649:   for(i=1;i<NCOVMAX;i++){
        !          13650:     DummyV[i]=0;
        !          13651:     FixedV[i]=0;
        !          13652:   }
        !          13653: 
        !          13654:   for(i=1; i <=ncovcol;i++){
        !          13655:     DummyV[i]=0;
        !          13656:     FixedV[i]=0;
        !          13657:   }
        !          13658:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
        !          13659:     DummyV[i]=1;
        !          13660:     FixedV[i]=0;
        !          13661:   }
        !          13662:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
        !          13663:     DummyV[i]=0;
        !          13664:     FixedV[i]=1;
        !          13665:   }
        !          13666:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
        !          13667:     DummyV[i]=1;
        !          13668:     FixedV[i]=1;
        !          13669:   }
        !          13670:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
        !          13671:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
        !          13672:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
        !          13673:   }
        !          13674: 
        !          13675: 
        !          13676: 
1.186     brouard  13677: /* Main decodemodel */
                   13678: 
1.187     brouard  13679: 
1.223     brouard  13680:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13681:     goto end;
                   13682: 
1.137     brouard  13683:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13684:     nbwarn++;
                   13685:     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); 
                   13686:     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); 
                   13687:   }
1.136     brouard  13688:     /*  if(mle==1){*/
1.137     brouard  13689:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13690:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13691:   }
                   13692: 
                   13693:     /*-calculation of age at interview from date of interview and age at death -*/
                   13694:   agev=matrix(1,maxwav,1,imx);
                   13695: 
                   13696:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13697:     goto end;
                   13698: 
1.126     brouard  13699: 
1.136     brouard  13700:   agegomp=(int)agemin;
1.290     brouard  13701:   free_vector(moisnais,firstobs,lastobs);
                   13702:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13703:   /* free_matrix(mint,1,maxwav,1,n);
                   13704:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13705:   /* free_vector(moisdc,1,n); */
                   13706:   /* free_vector(andc,1,n); */
1.145     brouard  13707:   /* */
                   13708:   
1.126     brouard  13709:   wav=ivector(1,imx);
1.214     brouard  13710:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13711:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13712:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13713:   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.*/
                   13714:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13715:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13716:    
                   13717:   /* Concatenates waves */
1.214     brouard  13718:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13719:      Death is a valid wave (if date is known).
                   13720:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13721:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13722:      and mw[mi+1][i]. dh depends on stepm.
                   13723:   */
                   13724: 
1.126     brouard  13725:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13726:   /* Concatenates waves */
1.145     brouard  13727:  
1.290     brouard  13728:   free_vector(moisdc,firstobs,lastobs);
                   13729:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13730: 
1.126     brouard  13731:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13732:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13733:   ncodemax[1]=1;
1.145     brouard  13734:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13735:   cptcoveff=0;
1.220     brouard  13736:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13737:     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  13738:   }
                   13739:   
                   13740:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13741:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13742:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13743:     invalidvarcomb[i]=0;
                   13744:   
1.211     brouard  13745:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13746:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13747:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13748:   
1.200     brouard  13749:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13750:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13751:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13752:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13753:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13754:    * (currently 0 or 1) in the data.
                   13755:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13756:    * corresponding modality (h,j).
                   13757:    */
                   13758: 
1.145     brouard  13759:   h=0;
                   13760:   /*if (cptcovn > 0) */
1.126     brouard  13761:   m=pow(2,cptcoveff);
                   13762:  
1.144     brouard  13763:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13764:           * For k=4 covariates, h goes from 1 to m=2**k
                   13765:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13766:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13767:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13768:           *______________________________   *______________________
                   13769:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13770:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13771:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13772:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13773:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13774:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13775:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13776:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13777:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13778:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13779:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13780:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13781:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13782:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13783:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13784:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13785:           */                                     
1.212     brouard  13786:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13787:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13788:      * and the value of each covariate?
                   13789:      * V1=1, V2=1, V3=2, V4=1 ?
                   13790:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13791:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13792:      * In order to get the real value in the data, we use nbcode
                   13793:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13794:      * We are keeping this crazy system in order to be able (in the future?) 
                   13795:      * to have more than 2 values (0 or 1) for a covariate.
                   13796:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13797:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13798:      *              bbbbbbbb
                   13799:      *              76543210     
                   13800:      *   h-1        00000101 (6-1=5)
1.219     brouard  13801:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13802:      *           &
                   13803:      *     1        00000001 (1)
1.219     brouard  13804:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13805:      *          +1= 00000001 =1 
1.211     brouard  13806:      *
                   13807:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13808:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13809:      *    >>k'            11
                   13810:      *          &   00000001
                   13811:      *            = 00000001
                   13812:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13813:      * Reverse h=6 and m=16?
                   13814:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13815:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13816:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13817:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13818:      * V3=decodtabm(14,3,2**4)=2
                   13819:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13820:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13821:      *          &1 000000001
                   13822:      *           = 000000001
                   13823:      *         +1= 000000010 =2
                   13824:      *                  2211
                   13825:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13826:      *                  V3=2
1.220     brouard  13827:                 * codtabm and decodtabm are identical
1.211     brouard  13828:      */
                   13829: 
1.145     brouard  13830: 
                   13831:  free_ivector(Ndum,-1,NCOVMAX);
                   13832: 
                   13833: 
1.126     brouard  13834:     
1.186     brouard  13835:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13836:   strcpy(optionfilegnuplot,optionfilefiname);
                   13837:   if(mle==-3)
1.201     brouard  13838:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13839:   strcat(optionfilegnuplot,".gp");
                   13840: 
                   13841:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13842:     printf("Problem with file %s",optionfilegnuplot);
                   13843:   }
                   13844:   else{
1.204     brouard  13845:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13846:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13847:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13848:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13849:   }
                   13850:   /*  fclose(ficgp);*/
1.186     brouard  13851: 
                   13852: 
                   13853:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13854: 
                   13855:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13856:   if(mle==-3)
1.201     brouard  13857:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13858:   strcat(optionfilehtm,".htm");
                   13859:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13860:     printf("Problem with %s \n",optionfilehtm);
                   13861:     exit(0);
1.126     brouard  13862:   }
                   13863: 
                   13864:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13865:   strcat(optionfilehtmcov,"-cov.htm");
                   13866:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13867:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13868:   }
                   13869:   else{
                   13870:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13871: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13872: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13873:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13874:   }
                   13875: 
1.335     brouard  13876:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13877: <title>IMaCh %s</title></head>\n\
                   13878:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13879: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13880: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13881: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13882: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13883:   
                   13884:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13885: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13886: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13887: 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  13888: \n\
                   13889: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13890:  <ul><li><h4>Parameter files</h4>\n\
                   13891:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13892:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13893:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13894:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13895:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13896:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13897:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13898:          fileres,fileres,\
                   13899:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13900:   fflush(fichtm);
                   13901: 
                   13902:   strcpy(pathr,path);
                   13903:   strcat(pathr,optionfilefiname);
1.184     brouard  13904: #ifdef WIN32
                   13905:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13906: #else
1.126     brouard  13907:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13908: #endif
                   13909:          
1.126     brouard  13910:   
1.220     brouard  13911:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13912:                 and for any valid combination of covariates
1.126     brouard  13913:      and prints on file fileres'p'. */
1.251     brouard  13914:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13915:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13916: 
                   13917:   fprintf(fichtm,"\n");
1.286     brouard  13918:   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  13919:          ftol, stepm);
                   13920:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13921:   ncurrv=1;
                   13922:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13923:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13924:   ncurrv=i;
                   13925:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13926:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13927:   ncurrv=i;
                   13928:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13929:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13930:   ncurrv=i;
                   13931:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13932:   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", \
                   13933:           nlstate, ndeath, maxwav, mle, weightopt);
                   13934: 
                   13935:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13936: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13937: 
                   13938:   
1.317     brouard  13939:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13940: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13941: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13942:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13943:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13944:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13945:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13946:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13947:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13948: 
1.126     brouard  13949:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13950:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13951:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13952: 
                   13953:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13954:   /* For mortality only */
1.126     brouard  13955:   if (mle==-3){
1.136     brouard  13956:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13957:     for(i=1;i<=NDIM;i++)
                   13958:       for(j=1;j<=NDIM;j++)
                   13959:        ximort[i][j]=0.;
1.186     brouard  13960:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13961:     cens=ivector(firstobs,lastobs);
                   13962:     ageexmed=vector(firstobs,lastobs);
                   13963:     agecens=vector(firstobs,lastobs);
                   13964:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13965:                
1.126     brouard  13966:     for (i=1; i<=imx; i++){
                   13967:       dcwave[i]=-1;
                   13968:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13969:        if (s[m][i]>nlstate) {
                   13970:          dcwave[i]=m;
                   13971:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13972:          break;
                   13973:        }
1.126     brouard  13974:     }
1.226     brouard  13975:     
1.126     brouard  13976:     for (i=1; i<=imx; i++) {
                   13977:       if (wav[i]>0){
1.226     brouard  13978:        ageexmed[i]=agev[mw[1][i]][i];
                   13979:        j=wav[i];
                   13980:        agecens[i]=1.; 
                   13981:        
                   13982:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13983:          agecens[i]=agev[mw[j][i]][i];
                   13984:          cens[i]= 1;
                   13985:        }else if (ageexmed[i]< 1) 
                   13986:          cens[i]= -1;
                   13987:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13988:          cens[i]=0 ;
1.126     brouard  13989:       }
                   13990:       else cens[i]=-1;
                   13991:     }
                   13992:     
                   13993:     for (i=1;i<=NDIM;i++) {
                   13994:       for (j=1;j<=NDIM;j++)
1.226     brouard  13995:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13996:     }
                   13997:     
1.302     brouard  13998:     p[1]=0.0268; p[NDIM]=0.083;
                   13999:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14000:     
                   14001:     
1.136     brouard  14002: #ifdef GSL
                   14003:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14004: #else
1.126     brouard  14005:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14006: #endif
1.201     brouard  14007:     strcpy(filerespow,"POW-MORT_"); 
                   14008:     strcat(filerespow,fileresu);
1.126     brouard  14009:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14010:       printf("Problem with resultfile: %s\n", filerespow);
                   14011:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14012:     }
1.136     brouard  14013: #ifdef GSL
                   14014:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14015: #else
1.126     brouard  14016:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14017: #endif
1.126     brouard  14018:     /*  for (i=1;i<=nlstate;i++)
                   14019:        for(j=1;j<=nlstate+ndeath;j++)
                   14020:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14021:     */
                   14022:     fprintf(ficrespow,"\n");
1.136     brouard  14023: #ifdef GSL
                   14024:     /* gsl starts here */ 
                   14025:     T = gsl_multimin_fminimizer_nmsimplex;
                   14026:     gsl_multimin_fminimizer *sfm = NULL;
                   14027:     gsl_vector *ss, *x;
                   14028:     gsl_multimin_function minex_func;
                   14029: 
                   14030:     /* Initial vertex size vector */
                   14031:     ss = gsl_vector_alloc (NDIM);
                   14032:     
                   14033:     if (ss == NULL){
                   14034:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14035:     }
                   14036:     /* Set all step sizes to 1 */
                   14037:     gsl_vector_set_all (ss, 0.001);
                   14038: 
                   14039:     /* Starting point */
1.126     brouard  14040:     
1.136     brouard  14041:     x = gsl_vector_alloc (NDIM);
                   14042:     
                   14043:     if (x == NULL){
                   14044:       gsl_vector_free(ss);
                   14045:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14046:     }
                   14047:   
                   14048:     /* Initialize method and iterate */
                   14049:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14050:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14051:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14052:     gsl_vector_set(x, 0, p[1]);
                   14053:     gsl_vector_set(x, 1, p[2]);
                   14054: 
                   14055:     minex_func.f = &gompertz_f;
                   14056:     minex_func.n = NDIM;
                   14057:     minex_func.params = (void *)&p; /* ??? */
                   14058:     
                   14059:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14060:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14061:     
                   14062:     printf("Iterations beginning .....\n\n");
                   14063:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14064: 
                   14065:     iteri=0;
                   14066:     while (rval == GSL_CONTINUE){
                   14067:       iteri++;
                   14068:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14069:       
                   14070:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14071:       fflush(0);
                   14072:       
                   14073:       if (status) 
                   14074:         break;
                   14075:       
                   14076:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14077:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14078:       
                   14079:       if (rval == GSL_SUCCESS)
                   14080:         printf ("converged to a local maximum at\n");
                   14081:       
                   14082:       printf("%5d ", iteri);
                   14083:       for (it = 0; it < NDIM; it++){
                   14084:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14085:       }
                   14086:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14087:     }
                   14088:     
                   14089:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14090:     
                   14091:     gsl_vector_free(x); /* initial values */
                   14092:     gsl_vector_free(ss); /* inital step size */
                   14093:     for (it=0; it<NDIM; it++){
                   14094:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14095:       fprintf(ficrespow," %.12lf", p[it]);
                   14096:     }
                   14097:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14098: #endif
                   14099: #ifdef POWELL
                   14100:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14101: #endif  
1.126     brouard  14102:     fclose(ficrespow);
                   14103:     
1.203     brouard  14104:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14105: 
                   14106:     for(i=1; i <=NDIM; i++)
                   14107:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14108:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14109:     
                   14110:     printf("\nCovariance matrix\n ");
1.203     brouard  14111:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14112:     for(i=1; i <=NDIM; i++) {
                   14113:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14114:                                printf("%f ",matcov[i][j]);
                   14115:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14116:       }
1.203     brouard  14117:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14118:     }
                   14119:     
                   14120:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14121:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14122:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14123:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14124:     }
1.302     brouard  14125:     lsurv=vector(agegomp,AGESUP);
                   14126:     lpop=vector(agegomp,AGESUP);
                   14127:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14128:     lsurv[agegomp]=100000;
                   14129:     
                   14130:     for (k=agegomp;k<=AGESUP;k++) {
                   14131:       agemortsup=k;
                   14132:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14133:     }
                   14134:     
                   14135:     for (k=agegomp;k<agemortsup;k++)
                   14136:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14137:     
                   14138:     for (k=agegomp;k<agemortsup;k++){
                   14139:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14140:       sumlpop=sumlpop+lpop[k];
                   14141:     }
                   14142:     
                   14143:     tpop[agegomp]=sumlpop;
                   14144:     for (k=agegomp;k<(agemortsup-3);k++){
                   14145:       /*  tpop[k+1]=2;*/
                   14146:       tpop[k+1]=tpop[k]-lpop[k];
                   14147:     }
                   14148:     
                   14149:     
                   14150:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14151:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14152:       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]);
                   14153:     
                   14154:     
                   14155:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14156:                ageminpar=50;
                   14157:                agemaxpar=100;
1.194     brouard  14158:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14159:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14160: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14161: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14162:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14163: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14164: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14165:     }else{
                   14166:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14167:                        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  14168:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14169:                }
1.201     brouard  14170:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14171:                     stepm, weightopt,\
                   14172:                     model,imx,p,matcov,agemortsup);
                   14173:     
1.302     brouard  14174:     free_vector(lsurv,agegomp,AGESUP);
                   14175:     free_vector(lpop,agegomp,AGESUP);
                   14176:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14177:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14178:     free_ivector(dcwave,firstobs,lastobs);
                   14179:     free_vector(agecens,firstobs,lastobs);
                   14180:     free_vector(ageexmed,firstobs,lastobs);
                   14181:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14182: #ifdef GSL
1.136     brouard  14183: #endif
1.186     brouard  14184:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14185:   /* Standard  */
                   14186:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14187:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14188:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14189:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14190:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14191:     for (k=1; k<=npar;k++)
                   14192:       printf(" %d %8.5f",k,p[k]);
                   14193:     printf("\n");
1.205     brouard  14194:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14195:       /* mlikeli uses func not funcone */
1.247     brouard  14196:       /* for(i=1;i<nlstate;i++){ */
                   14197:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14198:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14199:       /* } */
1.205     brouard  14200:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14201:     }
                   14202:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14203:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14204:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14205:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14206:     }
                   14207:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14208:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14209:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14210:           /* exit(0); */
1.126     brouard  14211:     for (k=1; k<=npar;k++)
                   14212:       printf(" %d %8.5f",k,p[k]);
                   14213:     printf("\n");
                   14214:     
                   14215:     /*--------- results files --------------*/
1.283     brouard  14216:     /* 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  14217:     
                   14218:     
                   14219:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14220:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14221:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14222: 
                   14223:     printf("#model=  1      +     age ");
                   14224:     fprintf(ficres,"#model=  1      +     age ");
                   14225:     fprintf(ficlog,"#model=  1      +     age ");
                   14226:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14227: </ul>", model);
                   14228: 
                   14229:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14230:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14231:     if(nagesqr==1){
                   14232:       printf("  + age*age  ");
                   14233:       fprintf(ficres,"  + age*age  ");
                   14234:       fprintf(ficlog,"  + age*age  ");
                   14235:       fprintf(fichtm, "<th>+ age*age</th>");
                   14236:     }
                   14237:     for(j=1;j <=ncovmodel-2;j++){
                   14238:       if(Typevar[j]==0) {
                   14239:        printf("  +      V%d  ",Tvar[j]);
                   14240:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14241:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14242:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14243:       }else if(Typevar[j]==1) {
                   14244:        printf("  +    V%d*age ",Tvar[j]);
                   14245:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14246:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14247:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14248:       }else if(Typevar[j]==2) {
                   14249:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14250:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14251:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14252:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349   ! brouard  14253:       }else if(Typevar[j]==3) { /* TO VERIFY */
        !          14254:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          14255:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          14256:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          14257:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14258:       }
                   14259:     }
                   14260:     printf("\n");
                   14261:     fprintf(ficres,"\n");
                   14262:     fprintf(ficlog,"\n");
                   14263:     fprintf(fichtm, "</tr>");
                   14264:     fprintf(fichtm, "\n");
                   14265:     
                   14266:     
1.126     brouard  14267:     for(i=1,jk=1; i <=nlstate; i++){
                   14268:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14269:        if (k != i) {
1.319     brouard  14270:          fprintf(fichtm, "<tr>");
1.225     brouard  14271:          printf("%d%d ",i,k);
                   14272:          fprintf(ficlog,"%d%d ",i,k);
                   14273:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14274:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14275:          for(j=1; j <=ncovmodel; j++){
                   14276:            printf("%12.7f ",p[jk]);
                   14277:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14278:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14279:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14280:            jk++; 
                   14281:          }
                   14282:          printf("\n");
                   14283:          fprintf(ficlog,"\n");
                   14284:          fprintf(ficres,"\n");
1.319     brouard  14285:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14286:        }
1.126     brouard  14287:       }
                   14288:     }
1.319     brouard  14289:     /* fprintf(fichtm,"</tr>\n"); */
                   14290:     fprintf(fichtm,"</table>\n");
                   14291:     fprintf(fichtm, "\n");
                   14292: 
1.203     brouard  14293:     if(mle != 0){
                   14294:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14295:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14296:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14297:       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");
                   14298:       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  14299:       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  14300:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14301:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14302:       if(nagesqr==1){
                   14303:        printf("  + age*age  ");
                   14304:        fprintf(ficres,"  + age*age  ");
                   14305:        fprintf(ficlog,"  + age*age  ");
                   14306:        fprintf(fichtm, "<th>+ age*age</th>");
                   14307:       }
                   14308:       for(j=1;j <=ncovmodel-2;j++){
                   14309:        if(Typevar[j]==0) {
                   14310:          printf("  +      V%d  ",Tvar[j]);
                   14311:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14312:        }else if(Typevar[j]==1) {
                   14313:          printf("  +    V%d*age ",Tvar[j]);
                   14314:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14315:        }else if(Typevar[j]==2) {
                   14316:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349   ! brouard  14317:        }else if(Typevar[j]==3) { /* TO VERIFY */
        !          14318:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14319:        }
                   14320:       }
                   14321:       fprintf(fichtm, "</tr>\n");
                   14322:  
1.203     brouard  14323:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14324:        for(k=1; k <=(nlstate+ndeath); k++){
                   14325:          if (k != i) {
1.319     brouard  14326:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14327:            printf("%d%d ",i,k);
                   14328:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14329:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14330:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14331:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14332:              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]));
                   14333:              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  14334:              if(fabs(wald) > 1.96){
1.321     brouard  14335:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14336:              }else{
                   14337:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14338:              }
1.324     brouard  14339:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14340:              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  14341:              jk++; 
                   14342:            }
                   14343:            printf("\n");
                   14344:            fprintf(ficlog,"\n");
1.319     brouard  14345:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14346:          }
                   14347:        }
1.193     brouard  14348:       }
1.203     brouard  14349:     } /* end of hesscov and Wald tests */
1.319     brouard  14350:     fprintf(fichtm,"</table>\n");
1.225     brouard  14351:     
1.203     brouard  14352:     /*  */
1.126     brouard  14353:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14354:     printf("# Scales (for hessian or gradient estimation)\n");
                   14355:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14356:     for(i=1,jk=1; i <=nlstate; i++){
                   14357:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14358:        if (j!=i) {
                   14359:          fprintf(ficres,"%1d%1d",i,j);
                   14360:          printf("%1d%1d",i,j);
                   14361:          fprintf(ficlog,"%1d%1d",i,j);
                   14362:          for(k=1; k<=ncovmodel;k++){
                   14363:            printf(" %.5e",delti[jk]);
                   14364:            fprintf(ficlog," %.5e",delti[jk]);
                   14365:            fprintf(ficres," %.5e",delti[jk]);
                   14366:            jk++;
                   14367:          }
                   14368:          printf("\n");
                   14369:          fprintf(ficlog,"\n");
                   14370:          fprintf(ficres,"\n");
                   14371:        }
1.126     brouard  14372:       }
                   14373:     }
                   14374:     
                   14375:     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.349   ! brouard  14376:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14377:       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");
                   14378:     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");
                   14379:     /* # 121 Var(a12)\n\ */
                   14380:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14381:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14382:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14383:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14384:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14385:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14386:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14387:     
                   14388:     
                   14389:     /* Just to have a covariance matrix which will be more understandable
                   14390:        even is we still don't want to manage dictionary of variables
                   14391:     */
                   14392:     for(itimes=1;itimes<=2;itimes++){
                   14393:       jj=0;
                   14394:       for(i=1; i <=nlstate; i++){
1.225     brouard  14395:        for(j=1; j <=nlstate+ndeath; j++){
                   14396:          if(j==i) continue;
                   14397:          for(k=1; k<=ncovmodel;k++){
                   14398:            jj++;
                   14399:            ca[0]= k+'a'-1;ca[1]='\0';
                   14400:            if(itimes==1){
                   14401:              if(mle>=1)
                   14402:                printf("#%1d%1d%d",i,j,k);
                   14403:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14404:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14405:            }else{
                   14406:              if(mle>=1)
                   14407:                printf("%1d%1d%d",i,j,k);
                   14408:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14409:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14410:            }
                   14411:            ll=0;
                   14412:            for(li=1;li <=nlstate; li++){
                   14413:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14414:                if(lj==li) continue;
                   14415:                for(lk=1;lk<=ncovmodel;lk++){
                   14416:                  ll++;
                   14417:                  if(ll<=jj){
                   14418:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14419:                    if(ll<jj){
                   14420:                      if(itimes==1){
                   14421:                        if(mle>=1)
                   14422:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14423:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14424:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14425:                      }else{
                   14426:                        if(mle>=1)
                   14427:                          printf(" %.5e",matcov[jj][ll]); 
                   14428:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14429:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14430:                      }
                   14431:                    }else{
                   14432:                      if(itimes==1){
                   14433:                        if(mle>=1)
                   14434:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14435:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14436:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14437:                      }else{
                   14438:                        if(mle>=1)
                   14439:                          printf(" %.7e",matcov[jj][ll]); 
                   14440:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14441:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14442:                      }
                   14443:                    }
                   14444:                  }
                   14445:                } /* end lk */
                   14446:              } /* end lj */
                   14447:            } /* end li */
                   14448:            if(mle>=1)
                   14449:              printf("\n");
                   14450:            fprintf(ficlog,"\n");
                   14451:            fprintf(ficres,"\n");
                   14452:            numlinepar++;
                   14453:          } /* end k*/
                   14454:        } /*end j */
1.126     brouard  14455:       } /* end i */
                   14456:     } /* end itimes */
                   14457:     
                   14458:     fflush(ficlog);
                   14459:     fflush(ficres);
1.225     brouard  14460:     while(fgets(line, MAXLINE, ficpar)) {
                   14461:       /* If line starts with a # it is a comment */
                   14462:       if (line[0] == '#') {
                   14463:        numlinepar++;
                   14464:        fputs(line,stdout);
                   14465:        fputs(line,ficparo);
                   14466:        fputs(line,ficlog);
1.299     brouard  14467:        fputs(line,ficres);
1.225     brouard  14468:        continue;
                   14469:       }else
                   14470:        break;
                   14471:     }
                   14472:     
1.209     brouard  14473:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14474:     /*   ungetc(c,ficpar); */
                   14475:     /*   fgets(line, MAXLINE, ficpar); */
                   14476:     /*   fputs(line,stdout); */
                   14477:     /*   fputs(line,ficparo); */
                   14478:     /* } */
                   14479:     /* ungetc(c,ficpar); */
1.126     brouard  14480:     
                   14481:     estepm=0;
1.209     brouard  14482:     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  14483:       
                   14484:       if (num_filled != 6) {
                   14485:        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);
                   14486:        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);
                   14487:        goto end;
                   14488:       }
                   14489:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14490:     }
                   14491:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14492:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14493:     
1.209     brouard  14494:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14495:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14496:     if (fage <= 2) {
                   14497:       bage = ageminpar;
                   14498:       fage = agemaxpar;
                   14499:     }
                   14500:     
                   14501:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14502:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14503:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14504:                
1.186     brouard  14505:     /* Other stuffs, more or less useful */    
1.254     brouard  14506:     while(fgets(line, MAXLINE, ficpar)) {
                   14507:       /* If line starts with a # it is a comment */
                   14508:       if (line[0] == '#') {
                   14509:        numlinepar++;
                   14510:        fputs(line,stdout);
                   14511:        fputs(line,ficparo);
                   14512:        fputs(line,ficlog);
1.299     brouard  14513:        fputs(line,ficres);
1.254     brouard  14514:        continue;
                   14515:       }else
                   14516:        break;
                   14517:     }
                   14518: 
                   14519:     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){
                   14520:       
                   14521:       if (num_filled != 7) {
                   14522:        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);
                   14523:        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);
                   14524:        goto end;
                   14525:       }
                   14526:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14527:       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);
                   14528:       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);
                   14529:       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  14530:     }
1.254     brouard  14531: 
                   14532:     while(fgets(line, MAXLINE, ficpar)) {
                   14533:       /* If line starts with a # it is a comment */
                   14534:       if (line[0] == '#') {
                   14535:        numlinepar++;
                   14536:        fputs(line,stdout);
                   14537:        fputs(line,ficparo);
                   14538:        fputs(line,ficlog);
1.299     brouard  14539:        fputs(line,ficres);
1.254     brouard  14540:        continue;
                   14541:       }else
                   14542:        break;
1.126     brouard  14543:     }
                   14544:     
                   14545:     
                   14546:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14547:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14548:     
1.254     brouard  14549:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14550:       if (num_filled != 1) {
                   14551:        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);
                   14552:        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);
                   14553:        goto end;
                   14554:       }
                   14555:       printf("pop_based=%d\n",popbased);
                   14556:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14557:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14558:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14559:     }
                   14560:      
1.258     brouard  14561:     /* Results */
1.332     brouard  14562:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14563:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14564:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14565:     endishere=0;
1.258     brouard  14566:     nresult=0;
1.308     brouard  14567:     parameterline=0;
1.258     brouard  14568:     do{
                   14569:       if(!fgets(line, MAXLINE, ficpar)){
                   14570:        endishere=1;
1.308     brouard  14571:        parameterline=15;
1.258     brouard  14572:       }else if (line[0] == '#') {
                   14573:        /* If line starts with a # it is a comment */
1.254     brouard  14574:        numlinepar++;
                   14575:        fputs(line,stdout);
                   14576:        fputs(line,ficparo);
                   14577:        fputs(line,ficlog);
1.299     brouard  14578:        fputs(line,ficres);
1.254     brouard  14579:        continue;
1.258     brouard  14580:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14581:        parameterline=11;
1.296     brouard  14582:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14583:        parameterline=12;
1.307     brouard  14584:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14585:        parameterline=13;
1.307     brouard  14586:       }
1.258     brouard  14587:       else{
                   14588:        parameterline=14;
1.254     brouard  14589:       }
1.308     brouard  14590:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14591:       case 11:
1.296     brouard  14592:        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)){
                   14593:                  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  14594:          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);
                   14595:          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);
                   14596:          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);
                   14597:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14598:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14599:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14600:           prvforecast = 1;
                   14601:        } 
                   14602:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14603:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14604:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14605:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14606:           prvforecast = 2;
                   14607:        }
                   14608:        else {
                   14609:          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);
                   14610:          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);
                   14611:          goto end;
1.258     brouard  14612:        }
1.254     brouard  14613:        break;
1.258     brouard  14614:       case 12:
1.296     brouard  14615:        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)){
                   14616:           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);
                   14617:          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);
                   14618:          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);
                   14619:          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);
                   14620:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14621:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14622:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14623:           prvbackcast = 1;
                   14624:        } 
                   14625:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14626:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14627:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14628:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14629:           prvbackcast = 2;
                   14630:        }
                   14631:        else {
                   14632:          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);
                   14633:          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);
                   14634:          goto end;
1.258     brouard  14635:        }
1.230     brouard  14636:        break;
1.258     brouard  14637:       case 13:
1.332     brouard  14638:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14639:        nresult++; /* Sum of resultlines */
1.342     brouard  14640:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14641:        /* removefirstspace(&resultlineori); */
                   14642:        
                   14643:        if(strstr(resultlineori,"v") !=0){
                   14644:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14645:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14646:          return 1;
                   14647:        }
                   14648:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14649:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14650:        if(nresult > MAXRESULTLINESPONE-1){
                   14651:          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);
                   14652:          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  14653:          goto end;
                   14654:        }
1.332     brouard  14655:        
1.310     brouard  14656:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14657:          fprintf(ficparo,"result: %s\n",resultline);
                   14658:          fprintf(ficres,"result: %s\n",resultline);
                   14659:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14660:        } else
                   14661:          goto end;
1.307     brouard  14662:        break;
                   14663:       case 14:
                   14664:        printf("Error: Unknown command '%s'\n",line);
                   14665:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14666:        if(line[0] == ' ' || line[0] == '\n'){
                   14667:          printf("It should not be an empty line '%s'\n",line);
                   14668:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14669:        }         
1.307     brouard  14670:        if(ncovmodel >=2 && nresult==0 ){
                   14671:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14672:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14673:        }
1.307     brouard  14674:        /* goto end; */
                   14675:        break;
1.308     brouard  14676:       case 15:
                   14677:        printf("End of resultlines.\n");
                   14678:        fprintf(ficlog,"End of resultlines.\n");
                   14679:        break;
                   14680:       default: /* parameterline =0 */
1.307     brouard  14681:        nresult=1;
                   14682:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14683:       } /* End switch parameterline */
                   14684:     }while(endishere==0); /* End do */
1.126     brouard  14685:     
1.230     brouard  14686:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14687:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14688:     
                   14689:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14690:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14691:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14692: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14693: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14694:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14695: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14696: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14697:     }else{
1.270     brouard  14698:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14699:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14700:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14701:       if(prvforecast==1){
                   14702:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14703:         jprojd=jproj1;
                   14704:         mprojd=mproj1;
                   14705:         anprojd=anproj1;
                   14706:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14707:         jprojf=jproj2;
                   14708:         mprojf=mproj2;
                   14709:         anprojf=anproj2;
                   14710:       } else if(prvforecast == 2){
                   14711:         dateprojd=dateintmean;
                   14712:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14713:         dateprojf=dateintmean+yrfproj;
                   14714:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14715:       }
                   14716:       if(prvbackcast==1){
                   14717:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14718:         jbackd=jback1;
                   14719:         mbackd=mback1;
                   14720:         anbackd=anback1;
                   14721:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14722:         jbackf=jback2;
                   14723:         mbackf=mback2;
                   14724:         anbackf=anback2;
                   14725:       } else if(prvbackcast == 2){
                   14726:         datebackd=dateintmean;
                   14727:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14728:         datebackf=dateintmean-yrbproj;
                   14729:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14730:       }
                   14731:       
                   14732:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14733:     }
                   14734:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14735:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14736:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14737:                
1.225     brouard  14738:     /*------------ free_vector  -------------*/
                   14739:     /*  chdir(path); */
1.220     brouard  14740:                
1.215     brouard  14741:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14742:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14743:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14744:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14745:     free_lvector(num,firstobs,lastobs);
                   14746:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14747:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14748:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14749:     fclose(ficparo);
                   14750:     fclose(ficres);
1.220     brouard  14751:                
                   14752:                
1.186     brouard  14753:     /* Other results (useful)*/
1.220     brouard  14754:                
                   14755:                
1.126     brouard  14756:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14757:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14758:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14759:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14760:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14761:     fclose(ficrespl);
                   14762: 
                   14763:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14764:     /*#include "hpijx.h"*/
1.332     brouard  14765:     /** 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?*/
                   14766:     /* calls hpxij with combination k */
1.180     brouard  14767:     hPijx(p, bage, fage);
1.145     brouard  14768:     fclose(ficrespij);
1.227     brouard  14769:     
1.220     brouard  14770:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14771:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14772:     k=1;
1.126     brouard  14773:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14774:     
1.269     brouard  14775:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14776:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14777:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14778:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14779:        for(k=1;k<=ncovcombmax;k++)
                   14780:          probs[i][j][k]=0.;
1.269     brouard  14781:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14782:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14783:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14784:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14785:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14786:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14787:          for(k=1;k<=ncovcombmax;k++)
                   14788:            mobaverages[i][j][k]=0.;
1.219     brouard  14789:       mobaverage=mobaverages;
                   14790:       if (mobilav!=0) {
1.235     brouard  14791:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14792:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14793:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14794:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14795:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14796:        }
1.269     brouard  14797:       } else if (mobilavproj !=0) {
1.235     brouard  14798:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14799:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14800:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14801:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14802:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14803:        }
1.269     brouard  14804:       }else{
                   14805:        printf("Internal error moving average\n");
                   14806:        fflush(stdout);
                   14807:        exit(1);
1.219     brouard  14808:       }
                   14809:     }/* end if moving average */
1.227     brouard  14810:     
1.126     brouard  14811:     /*---------- Forecasting ------------------*/
1.296     brouard  14812:     if(prevfcast==1){ 
                   14813:       /*   /\*    if(stepm ==1){*\/ */
                   14814:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14815:       /*This done previously after freqsummary.*/
                   14816:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14817:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14818:       
                   14819:       /* } else if (prvforecast==2){ */
                   14820:       /*   /\*    if(stepm ==1){*\/ */
                   14821:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14822:       /* } */
                   14823:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14824:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14825:     }
1.269     brouard  14826: 
1.296     brouard  14827:     /* Prevbcasting */
                   14828:     if(prevbcast==1){
1.219     brouard  14829:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14830:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14831:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14832: 
                   14833:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14834: 
                   14835:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14836: 
1.219     brouard  14837:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14838:       fclose(ficresplb);
                   14839: 
1.222     brouard  14840:       hBijx(p, bage, fage, mobaverage);
                   14841:       fclose(ficrespijb);
1.219     brouard  14842: 
1.296     brouard  14843:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14844:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14845:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14846:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14847:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14848:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14849: 
                   14850:       
1.269     brouard  14851:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14852: 
                   14853:       
1.269     brouard  14854:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14855:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14856:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14857:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14858:     }    /* end  Prevbcasting */
1.268     brouard  14859:  
1.186     brouard  14860:  
                   14861:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14862: 
1.215     brouard  14863:     free_ivector(wav,1,imx);
                   14864:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14865:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14866:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14867:                
                   14868:                
1.127     brouard  14869:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14870:                
1.201     brouard  14871:     strcpy(filerese,"E_");
                   14872:     strcat(filerese,fileresu);
1.126     brouard  14873:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14874:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14875:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14876:     }
1.208     brouard  14877:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14878:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14879: 
                   14880:     pstamp(ficreseij);
1.219     brouard  14881:                
1.235     brouard  14882:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14883:     if (cptcovn < 1){i1=1;}
                   14884:     
                   14885:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14886:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14887:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14888:        continue;
1.219     brouard  14889:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14890:       printf("\n#****** ");
1.225     brouard  14891:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14892:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14893:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14894:       }
                   14895:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14896:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14897:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14898:       }
                   14899:       fprintf(ficreseij,"******\n");
1.235     brouard  14900:       printf("******\n");
1.219     brouard  14901:       
                   14902:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14903:       oldm=oldms;savm=savms;
1.330     brouard  14904:       /* 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  14905:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14906:       
1.219     brouard  14907:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14908:     }
                   14909:     fclose(ficreseij);
1.208     brouard  14910:     printf("done evsij\n");fflush(stdout);
                   14911:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14912: 
1.218     brouard  14913:                
1.227     brouard  14914:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14915:     /* Should be moved in a function */                
1.201     brouard  14916:     strcpy(filerest,"T_");
                   14917:     strcat(filerest,fileresu);
1.127     brouard  14918:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14919:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14920:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14921:     }
1.208     brouard  14922:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14923:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14924:     strcpy(fileresstde,"STDE_");
                   14925:     strcat(fileresstde,fileresu);
1.126     brouard  14926:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14927:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14928:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14929:     }
1.227     brouard  14930:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14931:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14932: 
1.201     brouard  14933:     strcpy(filerescve,"CVE_");
                   14934:     strcat(filerescve,fileresu);
1.126     brouard  14935:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14936:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14937:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14938:     }
1.227     brouard  14939:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14940:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14941: 
1.201     brouard  14942:     strcpy(fileresv,"V_");
                   14943:     strcat(fileresv,fileresu);
1.126     brouard  14944:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14945:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14946:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14947:     }
1.227     brouard  14948:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14949:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14950: 
1.235     brouard  14951:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14952:     if (cptcovn < 1){i1=1;}
                   14953:     
1.334     brouard  14954:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14955:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14956:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14957:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14958:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14959:       /* */
                   14960:       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  14961:        continue;
1.321     brouard  14962:       printf("\n# model %s \n#****** Result for:", model);
                   14963:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14964:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14965:       /* It might not be a good idea to mix dummies and quantitative */
                   14966:       /* 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 *\/ */
                   14967:       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 */
                   14968:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14969:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14970:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14971:         * (V5 is quanti) V4 and V3 are dummies
                   14972:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14973:         *                                                              l=1 l=2
                   14974:         *                                                           k=1  1   1   0   0
                   14975:         *                                                           k=2  2   1   1   0
                   14976:         *                                                           k=3 [1] [2]  0   1
                   14977:         *                                                           k=4  2   2   1   1
                   14978:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14979:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14980:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14981:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14982:         */
                   14983:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14984:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14985: /* We give up with the combinations!! */
1.342     brouard  14986:        /* if(debugILK) */
                   14987:        /*   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  14988: 
                   14989:        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  14990:          /* 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] */
                   14991:          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  */
                   14992:          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  */
                   14993:          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  14994:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14995:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14996:          }else{
                   14997:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14998:          }
                   14999:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15000:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15001:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15002:          /* For each selected (single) quantitative value */
1.337     brouard  15003:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15004:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15005:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15006:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15007:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15008:          }else{
                   15009:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15010:          }
                   15011:        }else{
                   15012:          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 */
                   15013:          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 */
                   15014:          exit(1);
                   15015:        }
1.335     brouard  15016:       } /* End loop for each variable in the resultline */
1.334     brouard  15017:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15018:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15019:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15020:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15021:       /* }      */
1.208     brouard  15022:       fprintf(ficrest,"******\n");
1.227     brouard  15023:       fprintf(ficlog,"******\n");
                   15024:       printf("******\n");
1.208     brouard  15025:       
                   15026:       fprintf(ficresstdeij,"\n#****** ");
                   15027:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15028:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15029:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15030:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15031:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15032:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15033:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15034:       }
                   15035:       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  15036:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15037:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15038:       }        
1.208     brouard  15039:       fprintf(ficresstdeij,"******\n");
                   15040:       fprintf(ficrescveij,"******\n");
                   15041:       
                   15042:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15043:       /* pstamp(ficresvij); */
1.225     brouard  15044:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15045:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15046:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15047:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15048:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15049:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15050:       }        
1.208     brouard  15051:       fprintf(ficresvij,"******\n");
                   15052:       
                   15053:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15054:       oldm=oldms;savm=savms;
1.235     brouard  15055:       printf(" cvevsij ");
                   15056:       fprintf(ficlog, " cvevsij ");
                   15057:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15058:       printf(" end cvevsij \n ");
                   15059:       fprintf(ficlog, " end cvevsij \n ");
                   15060:       
                   15061:       /*
                   15062:        */
                   15063:       /* goto endfree; */
                   15064:       
                   15065:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15066:       pstamp(ficrest);
                   15067:       
1.269     brouard  15068:       epj=vector(1,nlstate+1);
1.208     brouard  15069:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15070:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15071:        cptcod= 0; /* To be deleted */
                   15072:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15073:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15074:        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  15075:        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 ");
                   15076:        if(vpopbased==1)
                   15077:          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);
                   15078:        else
1.288     brouard  15079:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15080:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15081:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15082:        fprintf(ficrest,"\n");
                   15083:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15084:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15085:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15086:        for(age=bage; age <=fage ;age++){
1.235     brouard  15087:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15088:          if (vpopbased==1) {
                   15089:            if(mobilav ==0){
                   15090:              for(i=1; i<=nlstate;i++)
                   15091:                prlim[i][i]=probs[(int)age][i][k];
                   15092:            }else{ /* mobilav */ 
                   15093:              for(i=1; i<=nlstate;i++)
                   15094:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15095:            }
                   15096:          }
1.219     brouard  15097:          
1.227     brouard  15098:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15099:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15100:          /* printf(" age %4.0f ",age); */
                   15101:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15102:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15103:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15104:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15105:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15106:            }
                   15107:            epj[nlstate+1] +=epj[j];
                   15108:          }
                   15109:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15110:          
1.227     brouard  15111:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15112:            for(j=1;j <=nlstate;j++)
                   15113:              vepp += vareij[i][j][(int)age];
                   15114:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15115:          for(j=1;j <=nlstate;j++){
                   15116:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15117:          }
                   15118:          fprintf(ficrest,"\n");
                   15119:        }
1.208     brouard  15120:       } /* End vpopbased */
1.269     brouard  15121:       free_vector(epj,1,nlstate+1);
1.208     brouard  15122:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15123:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15124:       printf("done selection\n");fflush(stdout);
                   15125:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15126:       
1.335     brouard  15127:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15128: 
                   15129:     printf("done State-specific expectancies\n");fflush(stdout);
                   15130:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15131: 
1.335     brouard  15132:     /* variance-covariance of forward period prevalence */
1.269     brouard  15133:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15134: 
1.227     brouard  15135:     
1.290     brouard  15136:     free_vector(weight,firstobs,lastobs);
1.349   ! brouard  15137:     free_imatrix(Tvardk,-1,NCOVMAX,1,2);
1.227     brouard  15138:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15139:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15140:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15141:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15142:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15143:     free_ivector(tab,1,NCOVMAX);
                   15144:     fclose(ficresstdeij);
                   15145:     fclose(ficrescveij);
                   15146:     fclose(ficresvij);
                   15147:     fclose(ficrest);
                   15148:     fclose(ficpar);
                   15149:     
                   15150:     
1.126     brouard  15151:     /*---------- End : free ----------------*/
1.219     brouard  15152:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15153:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15154:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15155:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15156:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15157:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15158:   /* endfree:*/
                   15159:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15160:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15161:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15162:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15163:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15164:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15165:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15166:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15167:   free_matrix(matcov,1,npar,1,npar);
                   15168:   free_matrix(hess,1,npar,1,npar);
                   15169:   /*free_vector(delti,1,npar);*/
                   15170:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15171:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15172:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15173:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15174:   
                   15175:   free_ivector(ncodemax,1,NCOVMAX);
                   15176:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15177:   free_ivector(Dummy,-1,NCOVMAX);
                   15178:   free_ivector(Fixed,-1,NCOVMAX);
1.349   ! brouard  15179:   free_ivector(DummyV,-1,NCOVMAX);
        !          15180:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15181:   free_ivector(Typevar,-1,NCOVMAX);
                   15182:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15183:   free_ivector(TvarsQ,1,NCOVMAX);
                   15184:   free_ivector(TvarsQind,1,NCOVMAX);
                   15185:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15186:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15187:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15188:   free_ivector(TvarFD,1,NCOVMAX);
                   15189:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15190:   free_ivector(TvarF,1,NCOVMAX);
                   15191:   free_ivector(TvarFind,1,NCOVMAX);
                   15192:   free_ivector(TvarV,1,NCOVMAX);
                   15193:   free_ivector(TvarVind,1,NCOVMAX);
                   15194:   free_ivector(TvarA,1,NCOVMAX);
                   15195:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15196:   free_ivector(TvarFQ,1,NCOVMAX);
                   15197:   free_ivector(TvarFQind,1,NCOVMAX);
                   15198:   free_ivector(TvarVD,1,NCOVMAX);
                   15199:   free_ivector(TvarVDind,1,NCOVMAX);
                   15200:   free_ivector(TvarVQ,1,NCOVMAX);
                   15201:   free_ivector(TvarVQind,1,NCOVMAX);
1.349   ! brouard  15202:   free_ivector(TvarAVVA,1,NCOVMAX);
        !          15203:   free_ivector(TvarAVVAind,1,NCOVMAX);
        !          15204:   free_ivector(TvarVVA,1,NCOVMAX);
        !          15205:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15206:   free_ivector(TvarVV,1,NCOVMAX);
                   15207:   free_ivector(TvarVVind,1,NCOVMAX);
                   15208:   
1.230     brouard  15209:   free_ivector(Tvarsel,1,NCOVMAX);
                   15210:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15211:   free_ivector(Tposprod,1,NCOVMAX);
                   15212:   free_ivector(Tprod,1,NCOVMAX);
                   15213:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15214:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15215:   free_ivector(Tage,1,NCOVMAX);
                   15216:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15217:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15218:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15219: 
                   15220:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15221: 
1.227     brouard  15222:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15223:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15224:   fflush(fichtm);
                   15225:   fflush(ficgp);
                   15226:   
1.227     brouard  15227:   
1.126     brouard  15228:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15229:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15230:     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  15231:   }else{
                   15232:     printf("End of Imach\n");
                   15233:     fprintf(ficlog,"End of Imach\n");
                   15234:   }
                   15235:   printf("See log file on %s\n",filelog);
                   15236:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15237:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15238:   rend_time = time(NULL);  
                   15239:   end_time = *localtime(&rend_time);
                   15240:   /* tml = *localtime(&end_time.tm_sec); */
                   15241:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15242:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15243:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15244:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15245:   
1.157     brouard  15246:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15247:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15248:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15249:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15250: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15251:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15252:   fclose(fichtm);
                   15253:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15254:   fclose(fichtmcov);
                   15255:   fclose(ficgp);
                   15256:   fclose(ficlog);
                   15257:   /*------ End -----------*/
1.227     brouard  15258:   
1.281     brouard  15259: 
                   15260: /* Executes gnuplot */
1.227     brouard  15261:   
                   15262:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15263: #ifdef WIN32
1.227     brouard  15264:   if (_chdir(pathcd) != 0)
                   15265:     printf("Can't move to directory %s!\n",path);
                   15266:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15267: #else
1.227     brouard  15268:     if(chdir(pathcd) != 0)
                   15269:       printf("Can't move to directory %s!\n", path);
                   15270:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15271: #endif 
1.126     brouard  15272:     printf("Current directory %s!\n",pathcd);
                   15273:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15274:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15275: #ifdef _WIN32
1.126     brouard  15276:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15277: #endif
                   15278:   if(!stat(plotcmd,&info)){
1.158     brouard  15279:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15280:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15281:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15282:     }else
                   15283:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15284: #ifdef __unix
1.126     brouard  15285:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15286:     if(!stat(plotcmd,&info)){
1.158     brouard  15287:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15288:     }else
                   15289:       strcpy(pplotcmd,plotcmd);
                   15290: #endif
                   15291:   }else
                   15292:     strcpy(pplotcmd,plotcmd);
                   15293:   
                   15294:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15295:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15296:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15297:   
1.126     brouard  15298:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15299:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15300:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15301:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15302:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15303:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15304:       strcpy(plotcmd,pplotcmd);
                   15305:     }
1.126     brouard  15306:   }
1.158     brouard  15307:   printf(" Successful, please wait...");
1.126     brouard  15308:   while (z[0] != 'q') {
                   15309:     /* chdir(path); */
1.154     brouard  15310:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15311:     scanf("%s",z);
                   15312: /*     if (z[0] == 'c') system("./imach"); */
                   15313:     if (z[0] == 'e') {
1.158     brouard  15314: #ifdef __APPLE__
1.152     brouard  15315:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15316: #elif __linux
                   15317:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15318: #else
1.152     brouard  15319:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15320: #endif
                   15321:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15322:       system(pplotcmd);
1.126     brouard  15323:     }
                   15324:     else if (z[0] == 'g') system(plotcmd);
                   15325:     else if (z[0] == 'q') exit(0);
                   15326:   }
1.227     brouard  15327: end:
1.126     brouard  15328:   while (z[0] != 'q') {
1.195     brouard  15329:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15330:     scanf("%s",z);
                   15331:   }
1.283     brouard  15332:   printf("End\n");
1.282     brouard  15333:   exit(0);
1.126     brouard  15334: }

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