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

1.351   ! brouard     1: /* $Id: imach.c,v 1.350 2023/04/24 11:38:06 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.351   ! brouard     4:   Revision 1.350  2023/04/24 11:38:06  brouard
        !             5:   *** empty log message ***
        !             6: 
1.350     brouard     7:   Revision 1.349  2023/01/31 09:19:37  brouard
                      8:   Summary: Improvements in models with age*Vn*Vm
                      9: 
1.348     brouard    10:   Revision 1.347  2022/09/18 14:36:44  brouard
                     11:   Summary: version 0.99r42
                     12: 
1.347     brouard    13:   Revision 1.346  2022/09/16 13:52:36  brouard
                     14:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     15: 
1.346     brouard    16:   Revision 1.345  2022/09/16 13:40:11  brouard
                     17:   Summary: Version 0.99r41
                     18: 
                     19:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     20: 
1.345     brouard    21:   Revision 1.344  2022/09/14 19:33:30  brouard
                     22:   Summary: version 0.99r40
                     23: 
                     24:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     25: 
1.344     brouard    26:   Revision 1.343  2022/09/14 14:22:16  brouard
                     27:   Summary: version 0.99r39
                     28: 
                     29:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     30:   (fixed or time varying), using new last columns of
                     31:   ILK_parameter.txt file.
                     32: 
1.343     brouard    33:   Revision 1.342  2022/09/11 19:54:09  brouard
                     34:   Summary: 0.99r38
                     35: 
                     36:   * imach.c (Module): Adding timevarying products of any kinds,
                     37:   should work before shifting cotvar from ncovcol+nqv columns in
                     38:   order to have a correspondance between the column of cotvar and
                     39:   the id of column.
                     40:   (Module): Some cleaning and adding covariates in ILK.txt
                     41: 
1.342     brouard    42:   Revision 1.341  2022/09/11 07:58:42  brouard
                     43:   Summary: Version 0.99r38
                     44: 
                     45:   After adding change in cotvar.
                     46: 
1.341     brouard    47:   Revision 1.340  2022/09/11 07:53:11  brouard
                     48:   Summary: Version imach 0.99r37
                     49: 
                     50:   * imach.c (Module): Adding timevarying products of any kinds,
                     51:   should work before shifting cotvar from ncovcol+nqv columns in
                     52:   order to have a correspondance between the column of cotvar and
                     53:   the id of column.
                     54: 
1.340     brouard    55:   Revision 1.339  2022/09/09 17:55:22  brouard
                     56:   Summary: version 0.99r37
                     57: 
                     58:   * imach.c (Module): Many improvements for fixing products of fixed
                     59:   timevarying as well as fixed * fixed, and test with quantitative
                     60:   covariate.
                     61: 
1.339     brouard    62:   Revision 1.338  2022/09/04 17:40:33  brouard
                     63:   Summary: 0.99r36
                     64: 
                     65:   * imach.c (Module): Now the easy runs i.e. without result or
                     66:   model=1+age only did not work. The defautl combination should be 1
                     67:   and not 0 because everything hasn't been tranformed yet.
                     68: 
1.338     brouard    69:   Revision 1.337  2022/09/02 14:26:02  brouard
                     70:   Summary: version 0.99r35
                     71: 
                     72:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     73:   1+age+V1+V1*age for females and 1+age for females only
                     74:   (education=1 noweight)
                     75: 
1.337     brouard    76:   Revision 1.336  2022/08/31 09:52:36  brouard
                     77:   *** empty log message ***
                     78: 
1.336     brouard    79:   Revision 1.335  2022/08/31 08:23:16  brouard
                     80:   Summary: improvements...
                     81: 
1.335     brouard    82:   Revision 1.334  2022/08/25 09:08:41  brouard
                     83:   Summary: In progress for quantitative
                     84: 
1.334     brouard    85:   Revision 1.333  2022/08/21 09:10:30  brouard
                     86:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     87:   reassigning covariates: my first idea was that people will always
                     88:   use the first covariate V1 into the model but in fact they are
                     89:   producing data with many covariates and can use an equation model
                     90:   with some of the covariate; it means that in a model V2+V3 instead
                     91:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     92:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     93:   the equation model is restricted to two variables only (V2, V3)
                     94:   and the combination for V2 should be codtabm(k,1) instead of
                     95:   (codtabm(k,2), and the code should be
                     96:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     97:   made. All of these should be simplified once a day like we did in
                     98:   hpxij() for example by using precov[nres] which is computed in
                     99:   decoderesult for each nres of each resultline. Loop should be done
                    100:   on the equation model globally by distinguishing only product with
                    101:   age (which are changing with age) and no more on type of
                    102:   covariates, single dummies, single covariates.
                    103: 
1.333     brouard   104:   Revision 1.332  2022/08/21 09:06:25  brouard
                    105:   Summary: Version 0.99r33
                    106: 
                    107:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    108:   reassigning covariates: my first idea was that people will always
                    109:   use the first covariate V1 into the model but in fact they are
                    110:   producing data with many covariates and can use an equation model
                    111:   with some of the covariate; it means that in a model V2+V3 instead
                    112:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    113:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    114:   the equation model is restricted to two variables only (V2, V3)
                    115:   and the combination for V2 should be codtabm(k,1) instead of
                    116:   (codtabm(k,2), and the code should be
                    117:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    118:   made. All of these should be simplified once a day like we did in
                    119:   hpxij() for example by using precov[nres] which is computed in
                    120:   decoderesult for each nres of each resultline. Loop should be done
                    121:   on the equation model globally by distinguishing only product with
                    122:   age (which are changing with age) and no more on type of
                    123:   covariates, single dummies, single covariates.
                    124: 
1.332     brouard   125:   Revision 1.331  2022/08/07 05:40:09  brouard
                    126:   *** empty log message ***
                    127: 
1.331     brouard   128:   Revision 1.330  2022/08/06 07:18:25  brouard
                    129:   Summary: last 0.99r31
                    130: 
                    131:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    132: 
1.330     brouard   133:   Revision 1.329  2022/08/03 17:29:54  brouard
                    134:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    135: 
1.329     brouard   136:   Revision 1.328  2022/07/27 17:40:48  brouard
                    137:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    138: 
1.328     brouard   139:   Revision 1.327  2022/07/27 14:47:35  brouard
                    140:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    141: 
1.327     brouard   142:   Revision 1.326  2022/07/26 17:33:55  brouard
                    143:   Summary: some test with nres=1
                    144: 
1.326     brouard   145:   Revision 1.325  2022/07/25 14:27:23  brouard
                    146:   Summary: r30
                    147: 
                    148:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    149:   coredumped, revealed by Feiuno, thank you.
                    150: 
1.325     brouard   151:   Revision 1.324  2022/07/23 17:44:26  brouard
                    152:   *** empty log message ***
                    153: 
1.324     brouard   154:   Revision 1.323  2022/07/22 12:30:08  brouard
                    155:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    156: 
1.323     brouard   157:   Revision 1.322  2022/07/22 12:27:48  brouard
                    158:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    159: 
1.322     brouard   160:   Revision 1.321  2022/07/22 12:04:24  brouard
                    161:   Summary: r28
                    162: 
                    163:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    164: 
1.321     brouard   165:   Revision 1.320  2022/06/02 05:10:11  brouard
                    166:   *** empty log message ***
                    167: 
1.320     brouard   168:   Revision 1.319  2022/06/02 04:45:11  brouard
                    169:   * imach.c (Module): Adding the Wald tests from the log to the main
                    170:   htm for better display of the maximum likelihood estimators.
                    171: 
1.319     brouard   172:   Revision 1.318  2022/05/24 08:10:59  brouard
                    173:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    174:   of confidencce intervals with product in the equation modelC
                    175: 
1.318     brouard   176:   Revision 1.317  2022/05/15 15:06:23  brouard
                    177:   * imach.c (Module):  Some minor improvements
                    178: 
1.317     brouard   179:   Revision 1.316  2022/05/11 15:11:31  brouard
                    180:   Summary: r27
                    181: 
1.316     brouard   182:   Revision 1.315  2022/05/11 15:06:32  brouard
                    183:   *** empty log message ***
                    184: 
1.315     brouard   185:   Revision 1.314  2022/04/13 17:43:09  brouard
                    186:   * imach.c (Module): Adding link to text data files
                    187: 
1.314     brouard   188:   Revision 1.313  2022/04/11 15:57:42  brouard
                    189:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    190: 
1.313     brouard   191:   Revision 1.312  2022/04/05 21:24:39  brouard
                    192:   *** empty log message ***
                    193: 
1.312     brouard   194:   Revision 1.311  2022/04/05 21:03:51  brouard
                    195:   Summary: Fixed quantitative covariates
                    196: 
                    197:          Fixed covariates (dummy or quantitative)
                    198:        with missing values have never been allowed but are ERRORS and
                    199:        program quits. Standard deviations of fixed covariates were
                    200:        wrongly computed. Mean and standard deviations of time varying
                    201:        covariates are still not computed.
                    202: 
1.311     brouard   203:   Revision 1.310  2022/03/17 08:45:53  brouard
                    204:   Summary: 99r25
                    205: 
                    206:   Improving detection of errors: result lines should be compatible with
                    207:   the model.
                    208: 
1.310     brouard   209:   Revision 1.309  2021/05/20 12:39:14  brouard
                    210:   Summary: Version 0.99r24
                    211: 
1.309     brouard   212:   Revision 1.308  2021/03/31 13:11:57  brouard
                    213:   Summary: Version 0.99r23
                    214: 
                    215: 
                    216:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    217: 
1.308     brouard   218:   Revision 1.307  2021/03/08 18:11:32  brouard
                    219:   Summary: 0.99r22 fixed bug on result:
                    220: 
1.307     brouard   221:   Revision 1.306  2021/02/20 15:44:02  brouard
                    222:   Summary: Version 0.99r21
                    223: 
                    224:   * imach.c (Module): Fix bug on quitting after result lines!
                    225:   (Module): Version 0.99r21
                    226: 
1.306     brouard   227:   Revision 1.305  2021/02/20 15:28:30  brouard
                    228:   * imach.c (Module): Fix bug on quitting after result lines!
                    229: 
1.305     brouard   230:   Revision 1.304  2021/02/12 11:34:20  brouard
                    231:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    232: 
1.304     brouard   233:   Revision 1.303  2021/02/11 19:50:15  brouard
                    234:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    235: 
1.303     brouard   236:   Revision 1.302  2020/02/22 21:00:05  brouard
                    237:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    238:   and life table from the data without any state)
                    239: 
1.302     brouard   240:   Revision 1.301  2019/06/04 13:51:20  brouard
                    241:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    242: 
1.301     brouard   243:   Revision 1.300  2019/05/22 19:09:45  brouard
                    244:   Summary: version 0.99r19 of May 2019
                    245: 
1.300     brouard   246:   Revision 1.299  2019/05/22 18:37:08  brouard
                    247:   Summary: Cleaned 0.99r19
                    248: 
1.299     brouard   249:   Revision 1.298  2019/05/22 18:19:56  brouard
                    250:   *** empty log message ***
                    251: 
1.298     brouard   252:   Revision 1.297  2019/05/22 17:56:10  brouard
                    253:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    254: 
1.297     brouard   255:   Revision 1.296  2019/05/20 13:03:18  brouard
                    256:   Summary: Projection syntax simplified
                    257: 
                    258: 
                    259:   We can now start projections, forward or backward, from the mean date
                    260:   of inteviews up to or down to a number of years of projection:
                    261:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    262:   or
                    263:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    264:   or
                    265:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    266:   or
                    267:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    268: 
1.296     brouard   269:   Revision 1.295  2019/05/18 09:52:50  brouard
                    270:   Summary: doxygen tex bug
                    271: 
1.295     brouard   272:   Revision 1.294  2019/05/16 14:54:33  brouard
                    273:   Summary: There was some wrong lines added
                    274: 
1.294     brouard   275:   Revision 1.293  2019/05/09 15:17:34  brouard
                    276:   *** empty log message ***
                    277: 
1.293     brouard   278:   Revision 1.292  2019/05/09 14:17:20  brouard
                    279:   Summary: Some updates
                    280: 
1.292     brouard   281:   Revision 1.291  2019/05/09 13:44:18  brouard
                    282:   Summary: Before ncovmax
                    283: 
1.291     brouard   284:   Revision 1.290  2019/05/09 13:39:37  brouard
                    285:   Summary: 0.99r18 unlimited number of individuals
                    286: 
                    287:   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.
                    288: 
1.290     brouard   289:   Revision 1.289  2018/12/13 09:16:26  brouard
                    290:   Summary: Bug for young ages (<-30) will be in r17
                    291: 
1.289     brouard   292:   Revision 1.288  2018/05/02 20:58:27  brouard
                    293:   Summary: Some bugs fixed
                    294: 
1.288     brouard   295:   Revision 1.287  2018/05/01 17:57:25  brouard
                    296:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    297: 
1.287     brouard   298:   Revision 1.286  2018/04/27 14:27:04  brouard
                    299:   Summary: some minor bugs
                    300: 
1.286     brouard   301:   Revision 1.285  2018/04/21 21:02:16  brouard
                    302:   Summary: Some bugs fixed, valgrind tested
                    303: 
1.285     brouard   304:   Revision 1.284  2018/04/20 05:22:13  brouard
                    305:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    306: 
1.284     brouard   307:   Revision 1.283  2018/04/19 14:49:16  brouard
                    308:   Summary: Some minor bugs fixed
                    309: 
1.283     brouard   310:   Revision 1.282  2018/02/27 22:50:02  brouard
                    311:   *** empty log message ***
                    312: 
1.282     brouard   313:   Revision 1.281  2018/02/27 19:25:23  brouard
                    314:   Summary: Adding second argument for quitting
                    315: 
1.281     brouard   316:   Revision 1.280  2018/02/21 07:58:13  brouard
                    317:   Summary: 0.99r15
                    318: 
                    319:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    320: 
1.280     brouard   321:   Revision 1.279  2017/07/20 13:35:01  brouard
                    322:   Summary: temporary working
                    323: 
1.279     brouard   324:   Revision 1.278  2017/07/19 14:09:02  brouard
                    325:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    326: 
1.278     brouard   327:   Revision 1.277  2017/07/17 08:53:49  brouard
                    328:   Summary: BOM files can be read now
                    329: 
1.277     brouard   330:   Revision 1.276  2017/06/30 15:48:31  brouard
                    331:   Summary: Graphs improvements
                    332: 
1.276     brouard   333:   Revision 1.275  2017/06/30 13:39:33  brouard
                    334:   Summary: Saito's color
                    335: 
1.275     brouard   336:   Revision 1.274  2017/06/29 09:47:08  brouard
                    337:   Summary: Version 0.99r14
                    338: 
1.274     brouard   339:   Revision 1.273  2017/06/27 11:06:02  brouard
                    340:   Summary: More documentation on projections
                    341: 
1.273     brouard   342:   Revision 1.272  2017/06/27 10:22:40  brouard
                    343:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    344: 
1.272     brouard   345:   Revision 1.271  2017/06/27 10:17:50  brouard
                    346:   Summary: Some bug with rint
                    347: 
1.271     brouard   348:   Revision 1.270  2017/05/24 05:45:29  brouard
                    349:   *** empty log message ***
                    350: 
1.270     brouard   351:   Revision 1.269  2017/05/23 08:39:25  brouard
                    352:   Summary: Code into subroutine, cleanings
                    353: 
1.269     brouard   354:   Revision 1.268  2017/05/18 20:09:32  brouard
                    355:   Summary: backprojection and confidence intervals of backprevalence
                    356: 
1.268     brouard   357:   Revision 1.267  2017/05/13 10:25:05  brouard
                    358:   Summary: temporary save for backprojection
                    359: 
1.267     brouard   360:   Revision 1.266  2017/05/13 07:26:12  brouard
                    361:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    362: 
1.266     brouard   363:   Revision 1.265  2017/04/26 16:22:11  brouard
                    364:   Summary: imach 0.99r13 Some bugs fixed
                    365: 
1.265     brouard   366:   Revision 1.264  2017/04/26 06:01:29  brouard
                    367:   Summary: Labels in graphs
                    368: 
1.264     brouard   369:   Revision 1.263  2017/04/24 15:23:15  brouard
                    370:   Summary: to save
                    371: 
1.263     brouard   372:   Revision 1.262  2017/04/18 16:48:12  brouard
                    373:   *** empty log message ***
                    374: 
1.262     brouard   375:   Revision 1.261  2017/04/05 10:14:09  brouard
                    376:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    377: 
1.261     brouard   378:   Revision 1.260  2017/04/04 17:46:59  brouard
                    379:   Summary: Gnuplot indexations fixed (humm)
                    380: 
1.260     brouard   381:   Revision 1.259  2017/04/04 13:01:16  brouard
                    382:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    383: 
1.259     brouard   384:   Revision 1.258  2017/04/03 10:17:47  brouard
                    385:   Summary: Version 0.99r12
                    386: 
                    387:   Some cleanings, conformed with updated documentation.
                    388: 
1.258     brouard   389:   Revision 1.257  2017/03/29 16:53:30  brouard
                    390:   Summary: Temp
                    391: 
1.257     brouard   392:   Revision 1.256  2017/03/27 05:50:23  brouard
                    393:   Summary: Temporary
                    394: 
1.256     brouard   395:   Revision 1.255  2017/03/08 16:02:28  brouard
                    396:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    397: 
1.255     brouard   398:   Revision 1.254  2017/03/08 07:13:00  brouard
                    399:   Summary: Fixing data parameter line
                    400: 
1.254     brouard   401:   Revision 1.253  2016/12/15 11:59:41  brouard
                    402:   Summary: 0.99 in progress
                    403: 
1.253     brouard   404:   Revision 1.252  2016/09/15 21:15:37  brouard
                    405:   *** empty log message ***
                    406: 
1.252     brouard   407:   Revision 1.251  2016/09/15 15:01:13  brouard
                    408:   Summary: not working
                    409: 
1.251     brouard   410:   Revision 1.250  2016/09/08 16:07:27  brouard
                    411:   Summary: continue
                    412: 
1.250     brouard   413:   Revision 1.249  2016/09/07 17:14:18  brouard
                    414:   Summary: Starting values from frequencies
                    415: 
1.249     brouard   416:   Revision 1.248  2016/09/07 14:10:18  brouard
                    417:   *** empty log message ***
                    418: 
1.248     brouard   419:   Revision 1.247  2016/09/02 11:11:21  brouard
                    420:   *** empty log message ***
                    421: 
1.247     brouard   422:   Revision 1.246  2016/09/02 08:49:22  brouard
                    423:   *** empty log message ***
                    424: 
1.246     brouard   425:   Revision 1.245  2016/09/02 07:25:01  brouard
                    426:   *** empty log message ***
                    427: 
1.245     brouard   428:   Revision 1.244  2016/09/02 07:17:34  brouard
                    429:   *** empty log message ***
                    430: 
1.244     brouard   431:   Revision 1.243  2016/09/02 06:45:35  brouard
                    432:   *** empty log message ***
                    433: 
1.243     brouard   434:   Revision 1.242  2016/08/30 15:01:20  brouard
                    435:   Summary: Fixing a lots
                    436: 
1.242     brouard   437:   Revision 1.241  2016/08/29 17:17:25  brouard
                    438:   Summary: gnuplot problem in Back projection to fix
                    439: 
1.241     brouard   440:   Revision 1.240  2016/08/29 07:53:18  brouard
                    441:   Summary: Better
                    442: 
1.240     brouard   443:   Revision 1.239  2016/08/26 15:51:03  brouard
                    444:   Summary: Improvement in Powell output in order to copy and paste
                    445: 
                    446:   Author:
                    447: 
1.239     brouard   448:   Revision 1.238  2016/08/26 14:23:35  brouard
                    449:   Summary: Starting tests of 0.99
                    450: 
1.238     brouard   451:   Revision 1.237  2016/08/26 09:20:19  brouard
                    452:   Summary: to valgrind
                    453: 
1.237     brouard   454:   Revision 1.236  2016/08/25 10:50:18  brouard
                    455:   *** empty log message ***
                    456: 
1.236     brouard   457:   Revision 1.235  2016/08/25 06:59:23  brouard
                    458:   *** empty log message ***
                    459: 
1.235     brouard   460:   Revision 1.234  2016/08/23 16:51:20  brouard
                    461:   *** empty log message ***
                    462: 
1.234     brouard   463:   Revision 1.233  2016/08/23 07:40:50  brouard
                    464:   Summary: not working
                    465: 
1.233     brouard   466:   Revision 1.232  2016/08/22 14:20:21  brouard
                    467:   Summary: not working
                    468: 
1.232     brouard   469:   Revision 1.231  2016/08/22 07:17:15  brouard
                    470:   Summary: not working
                    471: 
1.231     brouard   472:   Revision 1.230  2016/08/22 06:55:53  brouard
                    473:   Summary: Not working
                    474: 
1.230     brouard   475:   Revision 1.229  2016/07/23 09:45:53  brouard
                    476:   Summary: Completing for func too
                    477: 
1.229     brouard   478:   Revision 1.228  2016/07/22 17:45:30  brouard
                    479:   Summary: Fixing some arrays, still debugging
                    480: 
1.227     brouard   481:   Revision 1.226  2016/07/12 18:42:34  brouard
                    482:   Summary: temp
                    483: 
1.226     brouard   484:   Revision 1.225  2016/07/12 08:40:03  brouard
                    485:   Summary: saving but not running
                    486: 
1.225     brouard   487:   Revision 1.224  2016/07/01 13:16:01  brouard
                    488:   Summary: Fixes
                    489: 
1.224     brouard   490:   Revision 1.223  2016/02/19 09:23:35  brouard
                    491:   Summary: temporary
                    492: 
1.223     brouard   493:   Revision 1.222  2016/02/17 08:14:50  brouard
                    494:   Summary: Probably last 0.98 stable version 0.98r6
                    495: 
1.222     brouard   496:   Revision 1.221  2016/02/15 23:35:36  brouard
                    497:   Summary: minor bug
                    498: 
1.220     brouard   499:   Revision 1.219  2016/02/15 00:48:12  brouard
                    500:   *** empty log message ***
                    501: 
1.219     brouard   502:   Revision 1.218  2016/02/12 11:29:23  brouard
                    503:   Summary: 0.99 Back projections
                    504: 
1.218     brouard   505:   Revision 1.217  2015/12/23 17:18:31  brouard
                    506:   Summary: Experimental backcast
                    507: 
1.217     brouard   508:   Revision 1.216  2015/12/18 17:32:11  brouard
                    509:   Summary: 0.98r4 Warning and status=-2
                    510: 
                    511:   Version 0.98r4 is now:
                    512:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    513:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    514:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    515: 
1.216     brouard   516:   Revision 1.215  2015/12/16 08:52:24  brouard
                    517:   Summary: 0.98r4 working
                    518: 
1.215     brouard   519:   Revision 1.214  2015/12/16 06:57:54  brouard
                    520:   Summary: temporary not working
                    521: 
1.214     brouard   522:   Revision 1.213  2015/12/11 18:22:17  brouard
                    523:   Summary: 0.98r4
                    524: 
1.213     brouard   525:   Revision 1.212  2015/11/21 12:47:24  brouard
                    526:   Summary: minor typo
                    527: 
1.212     brouard   528:   Revision 1.211  2015/11/21 12:41:11  brouard
                    529:   Summary: 0.98r3 with some graph of projected cross-sectional
                    530: 
                    531:   Author: Nicolas Brouard
                    532: 
1.211     brouard   533:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   534:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   535:   Summary: Adding ftolpl parameter
                    536:   Author: N Brouard
                    537: 
                    538:   We had difficulties to get smoothed confidence intervals. It was due
                    539:   to the period prevalence which wasn't computed accurately. The inner
                    540:   parameter ftolpl is now an outer parameter of the .imach parameter
                    541:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    542:   computation are long.
                    543: 
1.209     brouard   544:   Revision 1.208  2015/11/17 14:31:57  brouard
                    545:   Summary: temporary
                    546: 
1.208     brouard   547:   Revision 1.207  2015/10/27 17:36:57  brouard
                    548:   *** empty log message ***
                    549: 
1.207     brouard   550:   Revision 1.206  2015/10/24 07:14:11  brouard
                    551:   *** empty log message ***
                    552: 
1.206     brouard   553:   Revision 1.205  2015/10/23 15:50:53  brouard
                    554:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    555: 
1.205     brouard   556:   Revision 1.204  2015/10/01 16:20:26  brouard
                    557:   Summary: Some new graphs of contribution to likelihood
                    558: 
1.204     brouard   559:   Revision 1.203  2015/09/30 17:45:14  brouard
                    560:   Summary: looking at better estimation of the hessian
                    561: 
                    562:   Also a better criteria for convergence to the period prevalence And
                    563:   therefore adding the number of years needed to converge. (The
                    564:   prevalence in any alive state shold sum to one
                    565: 
1.203     brouard   566:   Revision 1.202  2015/09/22 19:45:16  brouard
                    567:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    568: 
1.202     brouard   569:   Revision 1.201  2015/09/15 17:34:58  brouard
                    570:   Summary: 0.98r0
                    571: 
                    572:   - Some new graphs like suvival functions
                    573:   - Some bugs fixed like model=1+age+V2.
                    574: 
1.201     brouard   575:   Revision 1.200  2015/09/09 16:53:55  brouard
                    576:   Summary: Big bug thanks to Flavia
                    577: 
                    578:   Even model=1+age+V2. did not work anymore
                    579: 
1.200     brouard   580:   Revision 1.199  2015/09/07 14:09:23  brouard
                    581:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    582: 
1.199     brouard   583:   Revision 1.198  2015/09/03 07:14:39  brouard
                    584:   Summary: 0.98q5 Flavia
                    585: 
1.198     brouard   586:   Revision 1.197  2015/09/01 18:24:39  brouard
                    587:   *** empty log message ***
                    588: 
1.197     brouard   589:   Revision 1.196  2015/08/18 23:17:52  brouard
                    590:   Summary: 0.98q5
                    591: 
1.196     brouard   592:   Revision 1.195  2015/08/18 16:28:39  brouard
                    593:   Summary: Adding a hack for testing purpose
                    594: 
                    595:   After reading the title, ftol and model lines, if the comment line has
                    596:   a q, starting with #q, the answer at the end of the run is quit. It
                    597:   permits to run test files in batch with ctest. The former workaround was
                    598:   $ echo q | imach foo.imach
                    599: 
1.195     brouard   600:   Revision 1.194  2015/08/18 13:32:00  brouard
                    601:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    602: 
1.194     brouard   603:   Revision 1.193  2015/08/04 07:17:42  brouard
                    604:   Summary: 0.98q4
                    605: 
1.193     brouard   606:   Revision 1.192  2015/07/16 16:49:02  brouard
                    607:   Summary: Fixing some outputs
                    608: 
1.192     brouard   609:   Revision 1.191  2015/07/14 10:00:33  brouard
                    610:   Summary: Some fixes
                    611: 
1.191     brouard   612:   Revision 1.190  2015/05/05 08:51:13  brouard
                    613:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    614: 
                    615:   Fix 1+age+.
                    616: 
1.190     brouard   617:   Revision 1.189  2015/04/30 14:45:16  brouard
                    618:   Summary: 0.98q2
                    619: 
1.189     brouard   620:   Revision 1.188  2015/04/30 08:27:53  brouard
                    621:   *** empty log message ***
                    622: 
1.188     brouard   623:   Revision 1.187  2015/04/29 09:11:15  brouard
                    624:   *** empty log message ***
                    625: 
1.187     brouard   626:   Revision 1.186  2015/04/23 12:01:52  brouard
                    627:   Summary: V1*age is working now, version 0.98q1
                    628: 
                    629:   Some codes had been disabled in order to simplify and Vn*age was
                    630:   working in the optimization phase, ie, giving correct MLE parameters,
                    631:   but, as usual, outputs were not correct and program core dumped.
                    632: 
1.186     brouard   633:   Revision 1.185  2015/03/11 13:26:42  brouard
                    634:   Summary: Inclusion of compile and links command line for Intel Compiler
                    635: 
1.185     brouard   636:   Revision 1.184  2015/03/11 11:52:39  brouard
                    637:   Summary: Back from Windows 8. Intel Compiler
                    638: 
1.184     brouard   639:   Revision 1.183  2015/03/10 20:34:32  brouard
                    640:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    641: 
                    642:   We use directest instead of original Powell test; probably no
                    643:   incidence on the results, but better justifications;
                    644:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    645:   wrong results.
                    646: 
1.183     brouard   647:   Revision 1.182  2015/02/12 08:19:57  brouard
                    648:   Summary: Trying to keep directest which seems simpler and more general
                    649:   Author: Nicolas Brouard
                    650: 
1.182     brouard   651:   Revision 1.181  2015/02/11 23:22:24  brouard
                    652:   Summary: Comments on Powell added
                    653: 
                    654:   Author:
                    655: 
1.181     brouard   656:   Revision 1.180  2015/02/11 17:33:45  brouard
                    657:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    658: 
1.180     brouard   659:   Revision 1.179  2015/01/04 09:57:06  brouard
                    660:   Summary: back to OS/X
                    661: 
1.179     brouard   662:   Revision 1.178  2015/01/04 09:35:48  brouard
                    663:   *** empty log message ***
                    664: 
1.178     brouard   665:   Revision 1.177  2015/01/03 18:40:56  brouard
                    666:   Summary: Still testing ilc32 on OSX
                    667: 
1.177     brouard   668:   Revision 1.176  2015/01/03 16:45:04  brouard
                    669:   *** empty log message ***
                    670: 
1.176     brouard   671:   Revision 1.175  2015/01/03 16:33:42  brouard
                    672:   *** empty log message ***
                    673: 
1.175     brouard   674:   Revision 1.174  2015/01/03 16:15:49  brouard
                    675:   Summary: Still in cross-compilation
                    676: 
1.174     brouard   677:   Revision 1.173  2015/01/03 12:06:26  brouard
                    678:   Summary: trying to detect cross-compilation
                    679: 
1.173     brouard   680:   Revision 1.172  2014/12/27 12:07:47  brouard
                    681:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    682: 
1.172     brouard   683:   Revision 1.171  2014/12/23 13:26:59  brouard
                    684:   Summary: Back from Visual C
                    685: 
                    686:   Still problem with utsname.h on Windows
                    687: 
1.171     brouard   688:   Revision 1.170  2014/12/23 11:17:12  brouard
                    689:   Summary: Cleaning some \%% back to %%
                    690: 
                    691:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    692: 
1.170     brouard   693:   Revision 1.169  2014/12/22 23:08:31  brouard
                    694:   Summary: 0.98p
                    695: 
                    696:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    697: 
1.169     brouard   698:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   699:   Summary: update
1.169     brouard   700: 
1.168     brouard   701:   Revision 1.167  2014/12/22 13:50:56  brouard
                    702:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    703: 
                    704:   Testing on Linux 64
                    705: 
1.167     brouard   706:   Revision 1.166  2014/12/22 11:40:47  brouard
                    707:   *** empty log message ***
                    708: 
1.166     brouard   709:   Revision 1.165  2014/12/16 11:20:36  brouard
                    710:   Summary: After compiling on Visual C
                    711: 
                    712:   * imach.c (Module): Merging 1.61 to 1.162
                    713: 
1.165     brouard   714:   Revision 1.164  2014/12/16 10:52:11  brouard
                    715:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    716: 
                    717:   * imach.c (Module): Merging 1.61 to 1.162
                    718: 
1.164     brouard   719:   Revision 1.163  2014/12/16 10:30:11  brouard
                    720:   * imach.c (Module): Merging 1.61 to 1.162
                    721: 
1.163     brouard   722:   Revision 1.162  2014/09/25 11:43:39  brouard
                    723:   Summary: temporary backup 0.99!
                    724: 
1.162     brouard   725:   Revision 1.1  2014/09/16 11:06:58  brouard
                    726:   Summary: With some code (wrong) for nlopt
                    727: 
                    728:   Author:
                    729: 
                    730:   Revision 1.161  2014/09/15 20:41:41  brouard
                    731:   Summary: Problem with macro SQR on Intel compiler
                    732: 
1.161     brouard   733:   Revision 1.160  2014/09/02 09:24:05  brouard
                    734:   *** empty log message ***
                    735: 
1.160     brouard   736:   Revision 1.159  2014/09/01 10:34:10  brouard
                    737:   Summary: WIN32
                    738:   Author: Brouard
                    739: 
1.159     brouard   740:   Revision 1.158  2014/08/27 17:11:51  brouard
                    741:   *** empty log message ***
                    742: 
1.158     brouard   743:   Revision 1.157  2014/08/27 16:26:55  brouard
                    744:   Summary: Preparing windows Visual studio version
                    745:   Author: Brouard
                    746: 
                    747:   In order to compile on Visual studio, time.h is now correct and time_t
                    748:   and tm struct should be used. difftime should be used but sometimes I
                    749:   just make the differences in raw time format (time(&now).
                    750:   Trying to suppress #ifdef LINUX
                    751:   Add xdg-open for __linux in order to open default browser.
                    752: 
1.157     brouard   753:   Revision 1.156  2014/08/25 20:10:10  brouard
                    754:   *** empty log message ***
                    755: 
1.156     brouard   756:   Revision 1.155  2014/08/25 18:32:34  brouard
                    757:   Summary: New compile, minor changes
                    758:   Author: Brouard
                    759: 
1.155     brouard   760:   Revision 1.154  2014/06/20 17:32:08  brouard
                    761:   Summary: Outputs now all graphs of convergence to period prevalence
                    762: 
1.154     brouard   763:   Revision 1.153  2014/06/20 16:45:46  brouard
                    764:   Summary: If 3 live state, convergence to period prevalence on same graph
                    765:   Author: Brouard
                    766: 
1.153     brouard   767:   Revision 1.152  2014/06/18 17:54:09  brouard
                    768:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    769: 
1.152     brouard   770:   Revision 1.151  2014/06/18 16:43:30  brouard
                    771:   *** empty log message ***
                    772: 
1.151     brouard   773:   Revision 1.150  2014/06/18 16:42:35  brouard
                    774:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    775:   Author: brouard
                    776: 
1.150     brouard   777:   Revision 1.149  2014/06/18 15:51:14  brouard
                    778:   Summary: Some fixes in parameter files errors
                    779:   Author: Nicolas Brouard
                    780: 
1.149     brouard   781:   Revision 1.148  2014/06/17 17:38:48  brouard
                    782:   Summary: Nothing new
                    783:   Author: Brouard
                    784: 
                    785:   Just a new packaging for OS/X version 0.98nS
                    786: 
1.148     brouard   787:   Revision 1.147  2014/06/16 10:33:11  brouard
                    788:   *** empty log message ***
                    789: 
1.147     brouard   790:   Revision 1.146  2014/06/16 10:20:28  brouard
                    791:   Summary: Merge
                    792:   Author: Brouard
                    793: 
                    794:   Merge, before building revised version.
                    795: 
1.146     brouard   796:   Revision 1.145  2014/06/10 21:23:15  brouard
                    797:   Summary: Debugging with valgrind
                    798:   Author: Nicolas Brouard
                    799: 
                    800:   Lot of changes in order to output the results with some covariates
                    801:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    802:   improve the code.
                    803:   No more memory valgrind error but a lot has to be done in order to
                    804:   continue the work of splitting the code into subroutines.
                    805:   Also, decodemodel has been improved. Tricode is still not
                    806:   optimal. nbcode should be improved. Documentation has been added in
                    807:   the source code.
                    808: 
1.144     brouard   809:   Revision 1.143  2014/01/26 09:45:38  brouard
                    810:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    811: 
                    812:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    813:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    814: 
1.143     brouard   815:   Revision 1.142  2014/01/26 03:57:36  brouard
                    816:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    817: 
                    818:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    819: 
1.142     brouard   820:   Revision 1.141  2014/01/26 02:42:01  brouard
                    821:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    822: 
1.141     brouard   823:   Revision 1.140  2011/09/02 10:37:54  brouard
                    824:   Summary: times.h is ok with mingw32 now.
                    825: 
1.140     brouard   826:   Revision 1.139  2010/06/14 07:50:17  brouard
                    827:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    828:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    829: 
1.139     brouard   830:   Revision 1.138  2010/04/30 18:19:40  brouard
                    831:   *** empty log message ***
                    832: 
1.138     brouard   833:   Revision 1.137  2010/04/29 18:11:38  brouard
                    834:   (Module): Checking covariates for more complex models
                    835:   than V1+V2. A lot of change to be done. Unstable.
                    836: 
1.137     brouard   837:   Revision 1.136  2010/04/26 20:30:53  brouard
                    838:   (Module): merging some libgsl code. Fixing computation
                    839:   of likelione (using inter/intrapolation if mle = 0) in order to
                    840:   get same likelihood as if mle=1.
                    841:   Some cleaning of code and comments added.
                    842: 
1.136     brouard   843:   Revision 1.135  2009/10/29 15:33:14  brouard
                    844:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    845: 
1.135     brouard   846:   Revision 1.134  2009/10/29 13:18:53  brouard
                    847:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    848: 
1.134     brouard   849:   Revision 1.133  2009/07/06 10:21:25  brouard
                    850:   just nforces
                    851: 
1.133     brouard   852:   Revision 1.132  2009/07/06 08:22:05  brouard
                    853:   Many tings
                    854: 
1.132     brouard   855:   Revision 1.131  2009/06/20 16:22:47  brouard
                    856:   Some dimensions resccaled
                    857: 
1.131     brouard   858:   Revision 1.130  2009/05/26 06:44:34  brouard
                    859:   (Module): Max Covariate is now set to 20 instead of 8. A
                    860:   lot of cleaning with variables initialized to 0. Trying to make
                    861:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    862: 
1.130     brouard   863:   Revision 1.129  2007/08/31 13:49:27  lievre
                    864:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    865: 
1.129     lievre    866:   Revision 1.128  2006/06/30 13:02:05  brouard
                    867:   (Module): Clarifications on computing e.j
                    868: 
1.128     brouard   869:   Revision 1.127  2006/04/28 18:11:50  brouard
                    870:   (Module): Yes the sum of survivors was wrong since
                    871:   imach-114 because nhstepm was no more computed in the age
                    872:   loop. Now we define nhstepma in the age loop.
                    873:   (Module): In order to speed up (in case of numerous covariates) we
                    874:   compute health expectancies (without variances) in a first step
                    875:   and then all the health expectancies with variances or standard
                    876:   deviation (needs data from the Hessian matrices) which slows the
                    877:   computation.
                    878:   In the future we should be able to stop the program is only health
                    879:   expectancies and graph are needed without standard deviations.
                    880: 
1.127     brouard   881:   Revision 1.126  2006/04/28 17:23:28  brouard
                    882:   (Module): Yes the sum of survivors was wrong since
                    883:   imach-114 because nhstepm was no more computed in the age
                    884:   loop. Now we define nhstepma in the age loop.
                    885:   Version 0.98h
                    886: 
1.126     brouard   887:   Revision 1.125  2006/04/04 15:20:31  lievre
                    888:   Errors in calculation of health expectancies. Age was not initialized.
                    889:   Forecasting file added.
                    890: 
                    891:   Revision 1.124  2006/03/22 17:13:53  lievre
                    892:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    893:   The log-likelihood is printed in the log file
                    894: 
                    895:   Revision 1.123  2006/03/20 10:52:43  brouard
                    896:   * imach.c (Module): <title> changed, corresponds to .htm file
                    897:   name. <head> headers where missing.
                    898: 
                    899:   * imach.c (Module): Weights can have a decimal point as for
                    900:   English (a comma might work with a correct LC_NUMERIC environment,
                    901:   otherwise the weight is truncated).
                    902:   Modification of warning when the covariates values are not 0 or
                    903:   1.
                    904:   Version 0.98g
                    905: 
                    906:   Revision 1.122  2006/03/20 09:45:41  brouard
                    907:   (Module): Weights can have a decimal point as for
                    908:   English (a comma might work with a correct LC_NUMERIC environment,
                    909:   otherwise the weight is truncated).
                    910:   Modification of warning when the covariates values are not 0 or
                    911:   1.
                    912:   Version 0.98g
                    913: 
                    914:   Revision 1.121  2006/03/16 17:45:01  lievre
                    915:   * imach.c (Module): Comments concerning covariates added
                    916: 
                    917:   * imach.c (Module): refinements in the computation of lli if
                    918:   status=-2 in order to have more reliable computation if stepm is
                    919:   not 1 month. Version 0.98f
                    920: 
                    921:   Revision 1.120  2006/03/16 15:10:38  lievre
                    922:   (Module): refinements in the computation of lli if
                    923:   status=-2 in order to have more reliable computation if stepm is
                    924:   not 1 month. Version 0.98f
                    925: 
                    926:   Revision 1.119  2006/03/15 17:42:26  brouard
                    927:   (Module): Bug if status = -2, the loglikelihood was
                    928:   computed as likelihood omitting the logarithm. Version O.98e
                    929: 
                    930:   Revision 1.118  2006/03/14 18:20:07  brouard
                    931:   (Module): varevsij Comments added explaining the second
                    932:   table of variances if popbased=1 .
                    933:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    934:   (Module): Function pstamp added
                    935:   (Module): Version 0.98d
                    936: 
                    937:   Revision 1.117  2006/03/14 17:16:22  brouard
                    938:   (Module): varevsij Comments added explaining the second
                    939:   table of variances if popbased=1 .
                    940:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    941:   (Module): Function pstamp added
                    942:   (Module): Version 0.98d
                    943: 
                    944:   Revision 1.116  2006/03/06 10:29:27  brouard
                    945:   (Module): Variance-covariance wrong links and
                    946:   varian-covariance of ej. is needed (Saito).
                    947: 
                    948:   Revision 1.115  2006/02/27 12:17:45  brouard
                    949:   (Module): One freematrix added in mlikeli! 0.98c
                    950: 
                    951:   Revision 1.114  2006/02/26 12:57:58  brouard
                    952:   (Module): Some improvements in processing parameter
                    953:   filename with strsep.
                    954: 
                    955:   Revision 1.113  2006/02/24 14:20:24  brouard
                    956:   (Module): Memory leaks checks with valgrind and:
                    957:   datafile was not closed, some imatrix were not freed and on matrix
                    958:   allocation too.
                    959: 
                    960:   Revision 1.112  2006/01/30 09:55:26  brouard
                    961:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    962: 
                    963:   Revision 1.111  2006/01/25 20:38:18  brouard
                    964:   (Module): Lots of cleaning and bugs added (Gompertz)
                    965:   (Module): Comments can be added in data file. Missing date values
                    966:   can be a simple dot '.'.
                    967: 
                    968:   Revision 1.110  2006/01/25 00:51:50  brouard
                    969:   (Module): Lots of cleaning and bugs added (Gompertz)
                    970: 
                    971:   Revision 1.109  2006/01/24 19:37:15  brouard
                    972:   (Module): Comments (lines starting with a #) are allowed in data.
                    973: 
                    974:   Revision 1.108  2006/01/19 18:05:42  lievre
                    975:   Gnuplot problem appeared...
                    976:   To be fixed
                    977: 
                    978:   Revision 1.107  2006/01/19 16:20:37  brouard
                    979:   Test existence of gnuplot in imach path
                    980: 
                    981:   Revision 1.106  2006/01/19 13:24:36  brouard
                    982:   Some cleaning and links added in html output
                    983: 
                    984:   Revision 1.105  2006/01/05 20:23:19  lievre
                    985:   *** empty log message ***
                    986: 
                    987:   Revision 1.104  2005/09/30 16:11:43  lievre
                    988:   (Module): sump fixed, loop imx fixed, and simplifications.
                    989:   (Module): If the status is missing at the last wave but we know
                    990:   that the person is alive, then we can code his/her status as -2
                    991:   (instead of missing=-1 in earlier versions) and his/her
                    992:   contributions to the likelihood is 1 - Prob of dying from last
                    993:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    994:   the healthy state at last known wave). Version is 0.98
                    995: 
                    996:   Revision 1.103  2005/09/30 15:54:49  lievre
                    997:   (Module): sump fixed, loop imx fixed, and simplifications.
                    998: 
                    999:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1000:   Add the possibility to read data file including tab characters.
                   1001: 
                   1002:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1003:   Fix on curr_time
                   1004: 
                   1005:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1006:   Add version for Mac OS X. Just define UNIX in Makefile
                   1007: 
                   1008:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1009:   *** empty log message ***
                   1010: 
                   1011:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1012:   New version 0.97 . First attempt to estimate force of mortality
                   1013:   directly from the data i.e. without the need of knowing the health
                   1014:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1015:   This is the basic analysis of mortality and should be done before any
                   1016:   other analysis, in order to test if the mortality estimated from the
                   1017:   cross-longitudinal survey is different from the mortality estimated
                   1018:   from other sources like vital statistic data.
                   1019: 
                   1020:   The same imach parameter file can be used but the option for mle should be -3.
                   1021: 
1.324     brouard  1022:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1023:   former routines in order to include the new code within the former code.
                   1024: 
                   1025:   The output is very simple: only an estimate of the intercept and of
                   1026:   the slope with 95% confident intervals.
                   1027: 
                   1028:   Current limitations:
                   1029:   A) Even if you enter covariates, i.e. with the
                   1030:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1031:   B) There is no computation of Life Expectancy nor Life Table.
                   1032: 
                   1033:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1034:   Version 0.96d. Population forecasting command line is (temporarily)
                   1035:   suppressed.
                   1036: 
                   1037:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1038:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1039:   rewritten within the same printf. Workaround: many printfs.
                   1040: 
                   1041:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1042:   * imach.c (Repository):
                   1043:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1044:   matrix (cov(a12,c31) instead of numbers.
                   1045: 
                   1046:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1047:   Just cleaning
                   1048: 
                   1049:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1050:   (Module): On windows (cygwin) function asctime_r doesn't
                   1051:   exist so I changed back to asctime which exists.
                   1052:   (Module): Version 0.96b
                   1053: 
                   1054:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1055:   (Module): On windows (cygwin) function asctime_r doesn't
                   1056:   exist so I changed back to asctime which exists.
                   1057: 
                   1058:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1059:   * imach.c (Repository): Duplicated warning errors corrected.
                   1060:   (Repository): Elapsed time after each iteration is now output. It
                   1061:   helps to forecast when convergence will be reached. Elapsed time
                   1062:   is stamped in powell.  We created a new html file for the graphs
                   1063:   concerning matrix of covariance. It has extension -cov.htm.
                   1064: 
                   1065:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1066:   (Module): Some bugs corrected for windows. Also, when
                   1067:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1068:   of the covariance matrix to be input.
                   1069: 
                   1070:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1071:   (Module): Some bugs corrected for windows. Also, when
                   1072:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1073:   of the covariance matrix to be input.
                   1074: 
                   1075:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1076:   * 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.
                   1077: 
                   1078:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1079:   Version 0.96
                   1080: 
                   1081:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1082:   (Module): Change position of html and gnuplot routines and added
                   1083:   routine fileappend.
                   1084: 
                   1085:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1086:   * imach.c (Repository): Check when date of death was earlier that
                   1087:   current date of interview. It may happen when the death was just
                   1088:   prior to the death. In this case, dh was negative and likelihood
                   1089:   was wrong (infinity). We still send an "Error" but patch by
                   1090:   assuming that the date of death was just one stepm after the
                   1091:   interview.
                   1092:   (Repository): Because some people have very long ID (first column)
                   1093:   we changed int to long in num[] and we added a new lvector for
                   1094:   memory allocation. But we also truncated to 8 characters (left
                   1095:   truncation)
                   1096:   (Repository): No more line truncation errors.
                   1097: 
                   1098:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1099:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1100:   place. It differs from routine "prevalence" which may be called
                   1101:   many times. Probs is memory consuming and must be used with
                   1102:   parcimony.
                   1103:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1104: 
                   1105:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1106:   *** empty log message ***
                   1107: 
                   1108:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1109:   Add log in  imach.c and  fullversion number is now printed.
                   1110: 
                   1111: */
                   1112: /*
                   1113:    Interpolated Markov Chain
                   1114: 
                   1115:   Short summary of the programme:
                   1116:   
1.227     brouard  1117:   This program computes Healthy Life Expectancies or State-specific
                   1118:   (if states aren't health statuses) Expectancies from
                   1119:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1120: 
                   1121:   -1- a first survey ("cross") where individuals from different ages
                   1122:   are interviewed on their health status or degree of disability (in
                   1123:   the case of a health survey which is our main interest)
                   1124: 
                   1125:   -2- at least a second wave of interviews ("longitudinal") which
                   1126:   measure each change (if any) in individual health status.  Health
                   1127:   expectancies are computed from the time spent in each health state
                   1128:   according to a model. More health states you consider, more time is
                   1129:   necessary to reach the Maximum Likelihood of the parameters involved
                   1130:   in the model.  The simplest model is the multinomial logistic model
                   1131:   where pij is the probability to be observed in state j at the second
                   1132:   wave conditional to be observed in state i at the first
                   1133:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1134:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1135:   have a more complex model than "constant and age", you should modify
                   1136:   the program where the markup *Covariates have to be included here
                   1137:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1138:   convergence.
                   1139: 
                   1140:   The advantage of this computer programme, compared to a simple
                   1141:   multinomial logistic model, is clear when the delay between waves is not
                   1142:   identical for each individual. Also, if a individual missed an
                   1143:   intermediate interview, the information is lost, but taken into
                   1144:   account using an interpolation or extrapolation.  
                   1145: 
                   1146:   hPijx is the probability to be observed in state i at age x+h
                   1147:   conditional to the observed state i at age x. The delay 'h' can be
                   1148:   split into an exact number (nh*stepm) of unobserved intermediate
                   1149:   states. This elementary transition (by month, quarter,
                   1150:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1151:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1152:   and the contribution of each individual to the likelihood is simply
                   1153:   hPijx.
                   1154: 
                   1155:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1156:   of the life expectancies. It also computes the period (stable) prevalence.
                   1157: 
                   1158: Back prevalence and projections:
1.227     brouard  1159: 
                   1160:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1161:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1162:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1163:    mobilavproj)
                   1164: 
                   1165:     Computes the back prevalence limit for any combination of
                   1166:     covariate values k at any age between ageminpar and agemaxpar and
                   1167:     returns it in **bprlim. In the loops,
                   1168: 
                   1169:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1170:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1171: 
                   1172:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1173:    Computes for any combination of covariates k and any age between bage and fage 
                   1174:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1175:                        oldm=oldms;savm=savms;
1.227     brouard  1176: 
1.267     brouard  1177:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1178:      Computes the transition matrix starting at age 'age' over
                   1179:      'nhstepm*hstepm*stepm' months (i.e. until
                   1180:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1181:      nhstepm*hstepm matrices. 
                   1182: 
                   1183:      Returns p3mat[i][j][h] after calling
                   1184:      p3mat[i][j][h]=matprod2(newm,
                   1185:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1186:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1187:      oldm);
1.226     brouard  1188: 
                   1189: Important routines
                   1190: 
                   1191: - func (or funcone), computes logit (pij) distinguishing
                   1192:   o fixed variables (single or product dummies or quantitative);
                   1193:   o varying variables by:
                   1194:    (1) wave (single, product dummies, quantitative), 
                   1195:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1196:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1197:        % varying dummy (not done) or quantitative (not done);
                   1198: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1199:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1200: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1201:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1202:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1203: 
1.226     brouard  1204: 
                   1205:   
1.324     brouard  1206:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1207:            Institut national d'études démographiques, Paris.
1.126     brouard  1208:   This software have been partly granted by Euro-REVES, a concerted action
                   1209:   from the European Union.
                   1210:   It is copyrighted identically to a GNU software product, ie programme and
                   1211:   software can be distributed freely for non commercial use. Latest version
                   1212:   can be accessed at http://euroreves.ined.fr/imach .
                   1213: 
                   1214:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1215:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1216:   
                   1217:   **********************************************************************/
                   1218: /*
                   1219:   main
                   1220:   read parameterfile
                   1221:   read datafile
                   1222:   concatwav
                   1223:   freqsummary
                   1224:   if (mle >= 1)
                   1225:     mlikeli
                   1226:   print results files
                   1227:   if mle==1 
                   1228:      computes hessian
                   1229:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1230:       begin-prev-date,...
                   1231:   open gnuplot file
                   1232:   open html file
1.145     brouard  1233:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1234:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1235:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1236:     freexexit2 possible for memory heap.
                   1237: 
                   1238:   h Pij x                         | pij_nom  ficrestpij
                   1239:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1240:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1241:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1242: 
                   1243:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1244:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1245:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1246:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1247:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1248: 
1.126     brouard  1249:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1250:   health expectancies
                   1251:   Variance-covariance of DFLE
                   1252:   prevalence()
                   1253:    movingaverage()
                   1254:   varevsij() 
                   1255:   if popbased==1 varevsij(,popbased)
                   1256:   total life expectancies
                   1257:   Variance of period (stable) prevalence
                   1258:  end
                   1259: */
                   1260: 
1.187     brouard  1261: /* #define DEBUG */
                   1262: /* #define DEBUGBRENT */
1.203     brouard  1263: /* #define DEBUGLINMIN */
                   1264: /* #define DEBUGHESS */
                   1265: #define DEBUGHESSIJ
1.224     brouard  1266: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1267: #define POWELL /* Instead of NLOPT */
1.224     brouard  1268: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1269: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1270: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1271: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1272: 
                   1273: #include <math.h>
                   1274: #include <stdio.h>
                   1275: #include <stdlib.h>
                   1276: #include <string.h>
1.226     brouard  1277: #include <ctype.h>
1.159     brouard  1278: 
                   1279: #ifdef _WIN32
                   1280: #include <io.h>
1.172     brouard  1281: #include <windows.h>
                   1282: #include <tchar.h>
1.159     brouard  1283: #else
1.126     brouard  1284: #include <unistd.h>
1.159     brouard  1285: #endif
1.126     brouard  1286: 
                   1287: #include <limits.h>
                   1288: #include <sys/types.h>
1.171     brouard  1289: 
                   1290: #if defined(__GNUC__)
                   1291: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1292: #endif
                   1293: 
1.126     brouard  1294: #include <sys/stat.h>
                   1295: #include <errno.h>
1.159     brouard  1296: /* extern int errno; */
1.126     brouard  1297: 
1.157     brouard  1298: /* #ifdef LINUX */
                   1299: /* #include <time.h> */
                   1300: /* #include "timeval.h" */
                   1301: /* #else */
                   1302: /* #include <sys/time.h> */
                   1303: /* #endif */
                   1304: 
1.126     brouard  1305: #include <time.h>
                   1306: 
1.136     brouard  1307: #ifdef GSL
                   1308: #include <gsl/gsl_errno.h>
                   1309: #include <gsl/gsl_multimin.h>
                   1310: #endif
                   1311: 
1.167     brouard  1312: 
1.162     brouard  1313: #ifdef NLOPT
                   1314: #include <nlopt.h>
                   1315: typedef struct {
                   1316:   double (* function)(double [] );
                   1317: } myfunc_data ;
                   1318: #endif
                   1319: 
1.126     brouard  1320: /* #include <libintl.h> */
                   1321: /* #define _(String) gettext (String) */
                   1322: 
1.349     brouard  1323: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1324: 
                   1325: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1326: #define GNUPLOTVERSION 5.1
                   1327: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1328: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1329: #define FILENAMELENGTH 256
1.126     brouard  1330: 
                   1331: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1332: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1333: 
1.349     brouard  1334: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1335: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1336: 
                   1337: #define NINTERVMAX 8
1.144     brouard  1338: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1339: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1340: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1341: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1342: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1343: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1344: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1345: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1346: /* #define AGESUP 130 */
1.288     brouard  1347: /* #define AGESUP 150 */
                   1348: #define AGESUP 200
1.268     brouard  1349: #define AGEINF 0
1.218     brouard  1350: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1351: #define AGEBASE 40
1.194     brouard  1352: #define AGEOVERFLOW 1.e20
1.164     brouard  1353: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1354: #ifdef _WIN32
                   1355: #define DIRSEPARATOR '\\'
                   1356: #define CHARSEPARATOR "\\"
                   1357: #define ODIRSEPARATOR '/'
                   1358: #else
1.126     brouard  1359: #define DIRSEPARATOR '/'
                   1360: #define CHARSEPARATOR "/"
                   1361: #define ODIRSEPARATOR '\\'
                   1362: #endif
                   1363: 
1.351   ! brouard  1364: /* $Id: imach.c,v 1.350 2023/04/24 11:38:06 brouard Exp $ */
1.126     brouard  1365: /* $State: Exp $ */
1.196     brouard  1366: #include "version.h"
                   1367: char version[]=__IMACH_VERSION__;
1.349     brouard  1368: 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.351   ! brouard  1369: char fullversion[]="$Revision: 1.350 $ $Date: 2023/04/24 11:38:06 $"; 
1.126     brouard  1370: char strstart[80];
                   1371: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1372: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1373: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1374: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1375: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1376: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1377: 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  1378: 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  1379: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1380: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1381: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1382: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1383: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1384: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1385: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1386: 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  1387: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1388: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1389: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1390: 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 */
                   1391: 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 */
                   1392: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1393: 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  1394: int nsd=0; /**< Total number of single dummy variables (output) */
                   1395: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1396: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1397: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1398: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1399: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1400: int cptcov=0; /* Working variable */
1.334     brouard  1401: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1402: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1403: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1404: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1405: int nlstate=2; /* Number of live states */
                   1406: int ndeath=1; /* Number of dead states */
1.130     brouard  1407: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1408: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1409: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1410: int popbased=0;
                   1411: 
                   1412: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1413: int maxwav=0; /* Maxim number of waves */
                   1414: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1415: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1416: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1417:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1418: int mle=1, weightopt=0;
1.126     brouard  1419: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1420: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1421: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1422:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1423: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1424: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1425: 
1.130     brouard  1426: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1427: double **matprod2(); /* test */
1.126     brouard  1428: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1429: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1430: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1431: 
1.136     brouard  1432: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1433: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1434: FILE *ficlog, *ficrespow;
1.130     brouard  1435: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1436: double fretone; /* Only one call to likelihood */
1.130     brouard  1437: long ipmx=0; /* Number of contributions */
1.126     brouard  1438: double sw; /* Sum of weights */
                   1439: char filerespow[FILENAMELENGTH];
                   1440: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1441: FILE *ficresilk;
                   1442: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1443: FILE *ficresprobmorprev;
                   1444: FILE *fichtm, *fichtmcov; /* Html File */
                   1445: FILE *ficreseij;
                   1446: char filerese[FILENAMELENGTH];
                   1447: FILE *ficresstdeij;
                   1448: char fileresstde[FILENAMELENGTH];
                   1449: FILE *ficrescveij;
                   1450: char filerescve[FILENAMELENGTH];
                   1451: FILE  *ficresvij;
                   1452: char fileresv[FILENAMELENGTH];
1.269     brouard  1453: 
1.126     brouard  1454: char title[MAXLINE];
1.234     brouard  1455: char model[MAXLINE]; /**< The model line */
1.217     brouard  1456: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1457: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1458: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1459: char command[FILENAMELENGTH];
                   1460: int  outcmd=0;
                   1461: 
1.217     brouard  1462: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1463: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1464: char filelog[FILENAMELENGTH]; /* Log file */
                   1465: char filerest[FILENAMELENGTH];
                   1466: char fileregp[FILENAMELENGTH];
                   1467: char popfile[FILENAMELENGTH];
                   1468: 
                   1469: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1470: 
1.157     brouard  1471: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1472: /* struct timezone tzp; */
                   1473: /* extern int gettimeofday(); */
                   1474: struct tm tml, *gmtime(), *localtime();
                   1475: 
                   1476: extern time_t time();
                   1477: 
                   1478: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1479: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1480: time_t   rlast_btime; /* raw time */
1.157     brouard  1481: struct tm tm;
                   1482: 
1.126     brouard  1483: char strcurr[80], strfor[80];
                   1484: 
                   1485: char *endptr;
                   1486: long lval;
                   1487: double dval;
                   1488: 
                   1489: #define NR_END 1
                   1490: #define FREE_ARG char*
                   1491: #define FTOL 1.0e-10
                   1492: 
                   1493: #define NRANSI 
1.240     brouard  1494: #define ITMAX 200
                   1495: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1496: 
                   1497: #define TOL 2.0e-4 
                   1498: 
                   1499: #define CGOLD 0.3819660 
                   1500: #define ZEPS 1.0e-10 
                   1501: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1502: 
                   1503: #define GOLD 1.618034 
                   1504: #define GLIMIT 100.0 
                   1505: #define TINY 1.0e-20 
                   1506: 
                   1507: static double maxarg1,maxarg2;
                   1508: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1509: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1510:   
                   1511: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1512: #define rint(a) floor(a+0.5)
1.166     brouard  1513: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1514: #define mytinydouble 1.0e-16
1.166     brouard  1515: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1516: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1517: /* static double dsqrarg; */
                   1518: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1519: static double sqrarg;
                   1520: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1521: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1522: int agegomp= AGEGOMP;
                   1523: 
                   1524: int imx; 
                   1525: int stepm=1;
                   1526: /* Stepm, step in month: minimum step interpolation*/
                   1527: 
                   1528: int estepm;
                   1529: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1530: 
                   1531: int m,nb;
                   1532: long *num;
1.197     brouard  1533: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1534: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1535:                   covariate for which somebody answered excluding 
                   1536:                   undefined. Usually 2: 0 and 1. */
                   1537: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1538:                             covariate for which somebody answered including 
                   1539:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1540: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1541: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1542: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1543: 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  1544: double *ageexmed,*agecens;
                   1545: double dateintmean=0;
1.296     brouard  1546:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1547:   double anprojf, mprojf, jprojf;
1.126     brouard  1548: 
1.296     brouard  1549:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1550:   double anbackf, mbackf, jbackf;
                   1551:   double jintmean,mintmean,aintmean;  
1.126     brouard  1552: double *weight;
                   1553: int **s; /* Status */
1.141     brouard  1554: double *agedc;
1.145     brouard  1555: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1556:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1557:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1558: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1559: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1560: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1561: double  idx; 
                   1562: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1563: /* Some documentation */
                   1564:       /*   Design original data
                   1565:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1566:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1567:        *                                                             ntv=3     nqtv=1
1.330     brouard  1568:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1569:        * For time varying covariate, quanti or dummies
                   1570:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1571:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1572:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1573:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1574:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1575:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1576:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1577:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1578:        */
                   1579: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1580: /* 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
                   1581:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1582:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1583: */
1.349     brouard  1584: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1585: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1586: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1587:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1588:                                                                /* product without age, 3 for age and double product   */
                   1589: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1590:                                                                 /*(single or product without age), 2 dummy*/
                   1591:                                                                /* with age product, 3 quant with age product*/
                   1592: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1593: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1594: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1595: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1596: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1597: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1598: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1599: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1600: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1601: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1602: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1603: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1604: /* model="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+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   1605: /*  p Tvard[1][1]@21 = {6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}*/
                   1606: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>}
                   1607: /* p Tvardk[1][1]@24 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0}*/
                   1608: /* p Tvardk[1][1]@22 = {0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0} */
1.349     brouard  1609: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1610: /* 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  1611: /* 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  1612: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1613: /* Type                    */
                   1614: /* V         1  2  3  4  5 */
                   1615: /*           F  F  V  V  V */
                   1616: /*           D  Q  D  D  Q */
                   1617: /*                         */
                   1618: int *TvarsD;
1.330     brouard  1619: int *TnsdVar;
1.234     brouard  1620: int *TvarsDind;
                   1621: int *TvarsQ;
                   1622: int *TvarsQind;
                   1623: 
1.318     brouard  1624: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1625: int nresult=0;
1.258     brouard  1626: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1627: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1628: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1629: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1630: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1631: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1632: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1633: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1634: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1635: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1636: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1637: 
                   1638: /* 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
                   1639:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1640:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1641: */
1.234     brouard  1642: /* 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  1643: 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 */
                   1644: 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 */
                   1645: 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 */
                   1646: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1647: 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 */
                   1648: 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  1649: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1650: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1651: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1652: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1653: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1654: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1655: 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 */
                   1656: 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  1657: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1658: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1659: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1660: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1661: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1662: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1663:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1664:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1665:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1666:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1667:       /* 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  1668: int *Tvarsel; /**< Selected covariates for output */
                   1669: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1670: 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  1671: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1672: 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  1673: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1674: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1675: int *Tage;
1.227     brouard  1676: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1677: 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  1678: 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*/ 
                   1679: 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  1680: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1681: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1682: int **Tvard;
1.330     brouard  1683: int **Tvardk;
1.227     brouard  1684: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1685: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1686: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1687:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1688:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1689: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1690: double *lsurv, *lpop, *tpop;
                   1691: 
1.231     brouard  1692: #define FD 1; /* Fixed dummy covariate */
                   1693: #define FQ 2; /* Fixed quantitative covariate */
                   1694: #define FP 3; /* Fixed product covariate */
                   1695: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1696: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1697: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1698: #define VD 10; /* Varying dummy covariate */
                   1699: #define VQ 11; /* Varying quantitative covariate */
                   1700: #define VP 12; /* Varying product covariate */
                   1701: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1702: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1703: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1704: #define APFD 16; /* Age product * fixed dummy covariate */
                   1705: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1706: #define APVD 18; /* Age product * varying dummy covariate */
                   1707: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1708: 
                   1709: #define FTYPE 1; /* Fixed covariate */
                   1710: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1711: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1712: 
                   1713: struct kmodel{
                   1714:        int maintype; /* main type */
                   1715:        int subtype; /* subtype */
                   1716: };
                   1717: struct kmodel modell[NCOVMAX];
                   1718: 
1.143     brouard  1719: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1720: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1721: 
                   1722: /**************** split *************************/
                   1723: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1724: {
                   1725:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1726:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1727:   */ 
                   1728:   char *ss;                            /* pointer */
1.186     brouard  1729:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1730: 
                   1731:   l1 = strlen(path );                  /* length of path */
                   1732:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1733:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1734:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1735:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1736:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1737:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1738:     /* get current working directory */
                   1739:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1740: #ifdef WIN32
                   1741:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1742: #else
                   1743:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1744: #endif
1.126     brouard  1745:       return( GLOCK_ERROR_GETCWD );
                   1746:     }
                   1747:     /* got dirc from getcwd*/
                   1748:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1749:   } else {                             /* strip directory from path */
1.126     brouard  1750:     ss++;                              /* after this, the filename */
                   1751:     l2 = strlen( ss );                 /* length of filename */
                   1752:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1753:     strcpy( name, ss );                /* save file name */
                   1754:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1755:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1756:     printf(" DIRC2 = %s \n",dirc);
                   1757:   }
                   1758:   /* We add a separator at the end of dirc if not exists */
                   1759:   l1 = strlen( dirc );                 /* length of directory */
                   1760:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1761:     dirc[l1] =  DIRSEPARATOR;
                   1762:     dirc[l1+1] = 0; 
                   1763:     printf(" DIRC3 = %s \n",dirc);
                   1764:   }
                   1765:   ss = strrchr( name, '.' );           /* find last / */
                   1766:   if (ss >0){
                   1767:     ss++;
                   1768:     strcpy(ext,ss);                    /* save extension */
                   1769:     l1= strlen( name);
                   1770:     l2= strlen(ss)+1;
                   1771:     strncpy( finame, name, l1-l2);
                   1772:     finame[l1-l2]= 0;
                   1773:   }
                   1774: 
                   1775:   return( 0 );                         /* we're done */
                   1776: }
                   1777: 
                   1778: 
                   1779: /******************************************/
                   1780: 
                   1781: void replace_back_to_slash(char *s, char*t)
                   1782: {
                   1783:   int i;
                   1784:   int lg=0;
                   1785:   i=0;
                   1786:   lg=strlen(t);
                   1787:   for(i=0; i<= lg; i++) {
                   1788:     (s[i] = t[i]);
                   1789:     if (t[i]== '\\') s[i]='/';
                   1790:   }
                   1791: }
                   1792: 
1.132     brouard  1793: char *trimbb(char *out, char *in)
1.137     brouard  1794: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1795:   char *s;
                   1796:   s=out;
                   1797:   while (*in != '\0'){
1.137     brouard  1798:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1799:       in++;
                   1800:     }
                   1801:     *out++ = *in++;
                   1802:   }
                   1803:   *out='\0';
                   1804:   return s;
                   1805: }
                   1806: 
1.351   ! brouard  1807: char *trimbtab(char *out, char *in)
        !          1808: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
        !          1809:   char *s;
        !          1810:   s=out;
        !          1811:   while (*in != '\0'){
        !          1812:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
        !          1813:       in++;
        !          1814:     }
        !          1815:     *out++ = *in++;
        !          1816:   }
        !          1817:   *out='\0';
        !          1818:   return s;
        !          1819: }
        !          1820: 
1.187     brouard  1821: /* char *substrchaine(char *out, char *in, char *chain) */
                   1822: /* { */
                   1823: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1824: /*   char *s, *t; */
                   1825: /*   t=in;s=out; */
                   1826: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1827: /*     *out++ = *in++; */
                   1828: /*   } */
                   1829: 
                   1830: /*   /\* *in matches *chain *\/ */
                   1831: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1832: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1833: /*   } */
                   1834: /*   in--; chain--; */
                   1835: /*   while ( (*in != '\0')){ */
                   1836: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1837: /*     *out++ = *in++; */
                   1838: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1839: /*   } */
                   1840: /*   *out='\0'; */
                   1841: /*   out=s; */
                   1842: /*   return out; */
                   1843: /* } */
                   1844: char *substrchaine(char *out, char *in, char *chain)
                   1845: {
                   1846:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1847:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1848: 
                   1849:   char *strloc;
                   1850: 
1.349     brouard  1851:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1852:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1853:   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  1854:   if(strloc != NULL){ 
1.349     brouard  1855:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1856:     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)*/
                   1857:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1858:   }
1.349     brouard  1859:   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  1860:   return out;
                   1861: }
                   1862: 
                   1863: 
1.145     brouard  1864: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1865: {
1.187     brouard  1866:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1867:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1868:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1869:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1870:   */
1.160     brouard  1871:   char *s, *t;
1.145     brouard  1872:   t=in;s=in;
                   1873:   while ((*in != occ) && (*in != '\0')){
                   1874:     *alocc++ = *in++;
                   1875:   }
                   1876:   if( *in == occ){
                   1877:     *(alocc)='\0';
                   1878:     s=++in;
                   1879:   }
                   1880:  
                   1881:   if (s == t) {/* occ not found */
                   1882:     *(alocc-(in-s))='\0';
                   1883:     in=s;
                   1884:   }
                   1885:   while ( *in != '\0'){
                   1886:     *blocc++ = *in++;
                   1887:   }
                   1888: 
                   1889:   *blocc='\0';
                   1890:   return t;
                   1891: }
1.137     brouard  1892: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1893: {
1.187     brouard  1894:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1895:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1896:      gives blocc="abcdef2ghi" and alocc="j".
                   1897:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1898:   */
                   1899:   char *s, *t;
                   1900:   t=in;s=in;
                   1901:   while (*in != '\0'){
                   1902:     while( *in == occ){
                   1903:       *blocc++ = *in++;
                   1904:       s=in;
                   1905:     }
                   1906:     *blocc++ = *in++;
                   1907:   }
                   1908:   if (s == t) /* occ not found */
                   1909:     *(blocc-(in-s))='\0';
                   1910:   else
                   1911:     *(blocc-(in-s)-1)='\0';
                   1912:   in=s;
                   1913:   while ( *in != '\0'){
                   1914:     *alocc++ = *in++;
                   1915:   }
                   1916: 
                   1917:   *alocc='\0';
                   1918:   return s;
                   1919: }
                   1920: 
1.126     brouard  1921: int nbocc(char *s, char occ)
                   1922: {
                   1923:   int i,j=0;
                   1924:   int lg=20;
                   1925:   i=0;
                   1926:   lg=strlen(s);
                   1927:   for(i=0; i<= lg; i++) {
1.234     brouard  1928:     if  (s[i] == occ ) j++;
1.126     brouard  1929:   }
                   1930:   return j;
                   1931: }
                   1932: 
1.349     brouard  1933: int nboccstr(char *textin, char *chain)
                   1934: {
                   1935:   /* Counts the number of occurence of "chain"  in string textin */
                   1936:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1937:   char *strloc;
                   1938:   
                   1939:   int i,j=0;
                   1940: 
                   1941:   i=0;
                   1942: 
                   1943:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1944:   for(;;) {
                   1945:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1946:     if(strloc != NULL){
                   1947:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1948:       j++;
                   1949:     }else
                   1950:       break;
                   1951:   }
                   1952:   return j;
                   1953:   
                   1954: }
1.137     brouard  1955: /* void cutv(char *u,char *v, char*t, char occ) */
                   1956: /* { */
                   1957: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1958: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1959: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1960: /*   int i,lg,j,p=0; */
                   1961: /*   i=0; */
                   1962: /*   lg=strlen(t); */
                   1963: /*   for(j=0; j<=lg-1; j++) { */
                   1964: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1965: /*   } */
1.126     brouard  1966: 
1.137     brouard  1967: /*   for(j=0; j<p; j++) { */
                   1968: /*     (u[j] = t[j]); */
                   1969: /*   } */
                   1970: /*      u[p]='\0'; */
1.126     brouard  1971: 
1.137     brouard  1972: /*    for(j=0; j<= lg; j++) { */
                   1973: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1974: /*   } */
                   1975: /* } */
1.126     brouard  1976: 
1.160     brouard  1977: #ifdef _WIN32
                   1978: char * strsep(char **pp, const char *delim)
                   1979: {
                   1980:   char *p, *q;
                   1981:          
                   1982:   if ((p = *pp) == NULL)
                   1983:     return 0;
                   1984:   if ((q = strpbrk (p, delim)) != NULL)
                   1985:   {
                   1986:     *pp = q + 1;
                   1987:     *q = '\0';
                   1988:   }
                   1989:   else
                   1990:     *pp = 0;
                   1991:   return p;
                   1992: }
                   1993: #endif
                   1994: 
1.126     brouard  1995: /********************** nrerror ********************/
                   1996: 
                   1997: void nrerror(char error_text[])
                   1998: {
                   1999:   fprintf(stderr,"ERREUR ...\n");
                   2000:   fprintf(stderr,"%s\n",error_text);
                   2001:   exit(EXIT_FAILURE);
                   2002: }
                   2003: /*********************** vector *******************/
                   2004: double *vector(int nl, int nh)
                   2005: {
                   2006:   double *v;
                   2007:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2008:   if (!v) nrerror("allocation failure in vector");
                   2009:   return v-nl+NR_END;
                   2010: }
                   2011: 
                   2012: /************************ free vector ******************/
                   2013: void free_vector(double*v, int nl, int nh)
                   2014: {
                   2015:   free((FREE_ARG)(v+nl-NR_END));
                   2016: }
                   2017: 
                   2018: /************************ivector *******************************/
                   2019: int *ivector(long nl,long nh)
                   2020: {
                   2021:   int *v;
                   2022:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2023:   if (!v) nrerror("allocation failure in ivector");
                   2024:   return v-nl+NR_END;
                   2025: }
                   2026: 
                   2027: /******************free ivector **************************/
                   2028: void free_ivector(int *v, long nl, long nh)
                   2029: {
                   2030:   free((FREE_ARG)(v+nl-NR_END));
                   2031: }
                   2032: 
                   2033: /************************lvector *******************************/
                   2034: long *lvector(long nl,long nh)
                   2035: {
                   2036:   long *v;
                   2037:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2038:   if (!v) nrerror("allocation failure in ivector");
                   2039:   return v-nl+NR_END;
                   2040: }
                   2041: 
                   2042: /******************free lvector **************************/
                   2043: void free_lvector(long *v, long nl, long nh)
                   2044: {
                   2045:   free((FREE_ARG)(v+nl-NR_END));
                   2046: }
                   2047: 
                   2048: /******************* imatrix *******************************/
                   2049: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2050:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2051: { 
                   2052:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2053:   int **m; 
                   2054:   
                   2055:   /* allocate pointers to rows */ 
                   2056:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2057:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2058:   m += NR_END; 
                   2059:   m -= nrl; 
                   2060:   
                   2061:   
                   2062:   /* allocate rows and set pointers to them */ 
                   2063:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2064:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2065:   m[nrl] += NR_END; 
                   2066:   m[nrl] -= ncl; 
                   2067:   
                   2068:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2069:   
                   2070:   /* return pointer to array of pointers to rows */ 
                   2071:   return m; 
                   2072: } 
                   2073: 
                   2074: /****************** free_imatrix *************************/
                   2075: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2076:       int **m;
                   2077:       long nch,ncl,nrh,nrl; 
                   2078:      /* free an int matrix allocated by imatrix() */ 
                   2079: { 
                   2080:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2081:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2082: } 
                   2083: 
                   2084: /******************* matrix *******************************/
                   2085: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2086: {
                   2087:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2088:   double **m;
                   2089: 
                   2090:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2091:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2092:   m += NR_END;
                   2093:   m -= nrl;
                   2094: 
                   2095:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2096:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2097:   m[nrl] += NR_END;
                   2098:   m[nrl] -= ncl;
                   2099: 
                   2100:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2101:   return m;
1.145     brouard  2102:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2103: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2104: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2105:    */
                   2106: }
                   2107: 
                   2108: /*************************free matrix ************************/
                   2109: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2110: {
                   2111:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2112:   free((FREE_ARG)(m+nrl-NR_END));
                   2113: }
                   2114: 
                   2115: /******************* ma3x *******************************/
                   2116: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2117: {
                   2118:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2119:   double ***m;
                   2120: 
                   2121:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2122:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2123:   m += NR_END;
                   2124:   m -= nrl;
                   2125: 
                   2126:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2127:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2128:   m[nrl] += NR_END;
                   2129:   m[nrl] -= ncl;
                   2130: 
                   2131:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2132: 
                   2133:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2134:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2135:   m[nrl][ncl] += NR_END;
                   2136:   m[nrl][ncl] -= nll;
                   2137:   for (j=ncl+1; j<=nch; j++) 
                   2138:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2139:   
                   2140:   for (i=nrl+1; i<=nrh; i++) {
                   2141:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2142:     for (j=ncl+1; j<=nch; j++) 
                   2143:       m[i][j]=m[i][j-1]+nlay;
                   2144:   }
                   2145:   return m; 
                   2146:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2147:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2148:   */
                   2149: }
                   2150: 
                   2151: /*************************free ma3x ************************/
                   2152: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2153: {
                   2154:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2155:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2156:   free((FREE_ARG)(m+nrl-NR_END));
                   2157: }
                   2158: 
                   2159: /*************** function subdirf ***********/
                   2160: char *subdirf(char fileres[])
                   2161: {
                   2162:   /* Caution optionfilefiname is hidden */
                   2163:   strcpy(tmpout,optionfilefiname);
                   2164:   strcat(tmpout,"/"); /* Add to the right */
                   2165:   strcat(tmpout,fileres);
                   2166:   return tmpout;
                   2167: }
                   2168: 
                   2169: /*************** function subdirf2 ***********/
                   2170: char *subdirf2(char fileres[], char *preop)
                   2171: {
1.314     brouard  2172:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2173:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2174:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2175:   /* Caution optionfilefiname is hidden */
                   2176:   strcpy(tmpout,optionfilefiname);
                   2177:   strcat(tmpout,"/");
                   2178:   strcat(tmpout,preop);
                   2179:   strcat(tmpout,fileres);
                   2180:   return tmpout;
                   2181: }
                   2182: 
                   2183: /*************** function subdirf3 ***********/
                   2184: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2185: {
                   2186:   
                   2187:   /* Caution optionfilefiname is hidden */
                   2188:   strcpy(tmpout,optionfilefiname);
                   2189:   strcat(tmpout,"/");
                   2190:   strcat(tmpout,preop);
                   2191:   strcat(tmpout,preop2);
                   2192:   strcat(tmpout,fileres);
                   2193:   return tmpout;
                   2194: }
1.213     brouard  2195:  
                   2196: /*************** function subdirfext ***********/
                   2197: char *subdirfext(char fileres[], char *preop, char *postop)
                   2198: {
                   2199:   
                   2200:   strcpy(tmpout,preop);
                   2201:   strcat(tmpout,fileres);
                   2202:   strcat(tmpout,postop);
                   2203:   return tmpout;
                   2204: }
1.126     brouard  2205: 
1.213     brouard  2206: /*************** function subdirfext3 ***********/
                   2207: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2208: {
                   2209:   
                   2210:   /* Caution optionfilefiname is hidden */
                   2211:   strcpy(tmpout,optionfilefiname);
                   2212:   strcat(tmpout,"/");
                   2213:   strcat(tmpout,preop);
                   2214:   strcat(tmpout,fileres);
                   2215:   strcat(tmpout,postop);
                   2216:   return tmpout;
                   2217: }
                   2218:  
1.162     brouard  2219: char *asc_diff_time(long time_sec, char ascdiff[])
                   2220: {
                   2221:   long sec_left, days, hours, minutes;
                   2222:   days = (time_sec) / (60*60*24);
                   2223:   sec_left = (time_sec) % (60*60*24);
                   2224:   hours = (sec_left) / (60*60) ;
                   2225:   sec_left = (sec_left) %(60*60);
                   2226:   minutes = (sec_left) /60;
                   2227:   sec_left = (sec_left) % (60);
                   2228:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2229:   return ascdiff;
                   2230: }
                   2231: 
1.126     brouard  2232: /***************** f1dim *************************/
                   2233: extern int ncom; 
                   2234: extern double *pcom,*xicom;
                   2235: extern double (*nrfunc)(double []); 
                   2236:  
                   2237: double f1dim(double x) 
                   2238: { 
                   2239:   int j; 
                   2240:   double f;
                   2241:   double *xt; 
                   2242:  
                   2243:   xt=vector(1,ncom); 
                   2244:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2245:   f=(*nrfunc)(xt); 
                   2246:   free_vector(xt,1,ncom); 
                   2247:   return f; 
                   2248: } 
                   2249: 
                   2250: /*****************brent *************************/
                   2251: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2252: {
                   2253:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2254:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2255:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2256:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2257:    * returned function value. 
                   2258:   */
1.126     brouard  2259:   int iter; 
                   2260:   double a,b,d,etemp;
1.159     brouard  2261:   double fu=0,fv,fw,fx;
1.164     brouard  2262:   double ftemp=0.;
1.126     brouard  2263:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2264:   double e=0.0; 
                   2265:  
                   2266:   a=(ax < cx ? ax : cx); 
                   2267:   b=(ax > cx ? ax : cx); 
                   2268:   x=w=v=bx; 
                   2269:   fw=fv=fx=(*f)(x); 
                   2270:   for (iter=1;iter<=ITMAX;iter++) { 
                   2271:     xm=0.5*(a+b); 
                   2272:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2273:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2274:     printf(".");fflush(stdout);
                   2275:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2276: #ifdef DEBUGBRENT
1.126     brouard  2277:     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);
                   2278:     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);
                   2279:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2280: #endif
                   2281:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2282:       *xmin=x; 
                   2283:       return fx; 
                   2284:     } 
                   2285:     ftemp=fu;
                   2286:     if (fabs(e) > tol1) { 
                   2287:       r=(x-w)*(fx-fv); 
                   2288:       q=(x-v)*(fx-fw); 
                   2289:       p=(x-v)*q-(x-w)*r; 
                   2290:       q=2.0*(q-r); 
                   2291:       if (q > 0.0) p = -p; 
                   2292:       q=fabs(q); 
                   2293:       etemp=e; 
                   2294:       e=d; 
                   2295:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2296:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2297:       else { 
1.224     brouard  2298:                                d=p/q; 
                   2299:                                u=x+d; 
                   2300:                                if (u-a < tol2 || b-u < tol2) 
                   2301:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2302:       } 
                   2303:     } else { 
                   2304:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2305:     } 
                   2306:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2307:     fu=(*f)(u); 
                   2308:     if (fu <= fx) { 
                   2309:       if (u >= x) a=x; else b=x; 
                   2310:       SHFT(v,w,x,u) 
1.183     brouard  2311:       SHFT(fv,fw,fx,fu) 
                   2312:     } else { 
                   2313:       if (u < x) a=u; else b=u; 
                   2314:       if (fu <= fw || w == x) { 
1.224     brouard  2315:                                v=w; 
                   2316:                                w=u; 
                   2317:                                fv=fw; 
                   2318:                                fw=fu; 
1.183     brouard  2319:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2320:                                v=u; 
                   2321:                                fv=fu; 
1.183     brouard  2322:       } 
                   2323:     } 
1.126     brouard  2324:   } 
                   2325:   nrerror("Too many iterations in brent"); 
                   2326:   *xmin=x; 
                   2327:   return fx; 
                   2328: } 
                   2329: 
                   2330: /****************** mnbrak ***********************/
                   2331: 
                   2332: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2333:            double (*func)(double)) 
1.183     brouard  2334: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2335: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2336: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2337: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2338:    */
1.126     brouard  2339:   double ulim,u,r,q, dum;
                   2340:   double fu; 
1.187     brouard  2341: 
                   2342:   double scale=10.;
                   2343:   int iterscale=0;
                   2344: 
                   2345:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2346:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2347: 
                   2348: 
                   2349:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2350:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2351:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2352:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2353:   /* } */
                   2354: 
1.126     brouard  2355:   if (*fb > *fa) { 
                   2356:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2357:     SHFT(dum,*fb,*fa,dum) 
                   2358:   } 
1.126     brouard  2359:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2360:   *fc=(*func)(*cx); 
1.183     brouard  2361: #ifdef DEBUG
1.224     brouard  2362:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2363:   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  2364: #endif
1.224     brouard  2365:   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  2366:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2367:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2368:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2369:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2370:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2371:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2372:       fu=(*func)(u); 
1.163     brouard  2373: #ifdef DEBUG
                   2374:       /* f(x)=A(x-u)**2+f(u) */
                   2375:       double A, fparabu; 
                   2376:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2377:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2378:       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);
                   2379:       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  2380:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2381:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2382:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2383:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2384: #endif 
1.184     brouard  2385: #ifdef MNBRAKORIGINAL
1.183     brouard  2386: #else
1.191     brouard  2387: /*       if (fu > *fc) { */
                   2388: /* #ifdef DEBUG */
                   2389: /*       printf("mnbrak4  fu > fc \n"); */
                   2390: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2391: /* #endif */
                   2392: /*     /\* 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 *\\/  *\/ */
                   2393: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2394: /*     dum=u; /\* Shifting c and u *\/ */
                   2395: /*     u = *cx; */
                   2396: /*     *cx = dum; */
                   2397: /*     dum = fu; */
                   2398: /*     fu = *fc; */
                   2399: /*     *fc =dum; */
                   2400: /*       } else { /\* end *\/ */
                   2401: /* #ifdef DEBUG */
                   2402: /*       printf("mnbrak3  fu < fc \n"); */
                   2403: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2404: /* #endif */
                   2405: /*     dum=u; /\* Shifting c and u *\/ */
                   2406: /*     u = *cx; */
                   2407: /*     *cx = dum; */
                   2408: /*     dum = fu; */
                   2409: /*     fu = *fc; */
                   2410: /*     *fc =dum; */
                   2411: /*       } */
1.224     brouard  2412: #ifdef DEBUGMNBRAK
                   2413:                 double A, fparabu; 
                   2414:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2415:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2416:      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);
                   2417:      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  2418: #endif
1.191     brouard  2419:       dum=u; /* Shifting c and u */
                   2420:       u = *cx;
                   2421:       *cx = dum;
                   2422:       dum = fu;
                   2423:       fu = *fc;
                   2424:       *fc =dum;
1.183     brouard  2425: #endif
1.162     brouard  2426:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2427: #ifdef DEBUG
1.224     brouard  2428:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2429:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2430: #endif
1.126     brouard  2431:       fu=(*func)(u); 
                   2432:       if (fu < *fc) { 
1.183     brouard  2433: #ifdef DEBUG
1.224     brouard  2434:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2435:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2436: #endif
                   2437:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2438:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2439: #ifdef DEBUG
                   2440:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2441: #endif
                   2442:       } 
1.162     brouard  2443:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2444: #ifdef DEBUG
1.224     brouard  2445:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2446:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2447: #endif
1.126     brouard  2448:       u=ulim; 
                   2449:       fu=(*func)(u); 
1.183     brouard  2450:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2451: #ifdef DEBUG
1.224     brouard  2452:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2453:       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  2454: #endif
1.126     brouard  2455:       u=(*cx)+GOLD*(*cx-*bx); 
                   2456:       fu=(*func)(u); 
1.224     brouard  2457: #ifdef DEBUG
                   2458:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2459:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2460: #endif
1.183     brouard  2461:     } /* end tests */
1.126     brouard  2462:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2463:     SHFT(*fa,*fb,*fc,fu) 
                   2464: #ifdef DEBUG
1.224     brouard  2465:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2466:       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  2467: #endif
                   2468:   } /* 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  2469: } 
                   2470: 
                   2471: /*************** linmin ************************/
1.162     brouard  2472: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2473: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2474: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2475: the value of func at the returned location p . This is actually all accomplished by calling the
                   2476: routines mnbrak and brent .*/
1.126     brouard  2477: int ncom; 
                   2478: double *pcom,*xicom;
                   2479: double (*nrfunc)(double []); 
                   2480:  
1.224     brouard  2481: #ifdef LINMINORIGINAL
1.126     brouard  2482: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2483: #else
                   2484: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2485: #endif
1.126     brouard  2486: { 
                   2487:   double brent(double ax, double bx, double cx, 
                   2488:               double (*f)(double), double tol, double *xmin); 
                   2489:   double f1dim(double x); 
                   2490:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2491:              double *fc, double (*func)(double)); 
                   2492:   int j; 
                   2493:   double xx,xmin,bx,ax; 
                   2494:   double fx,fb,fa;
1.187     brouard  2495: 
1.203     brouard  2496: #ifdef LINMINORIGINAL
                   2497: #else
                   2498:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2499: #endif
                   2500:   
1.126     brouard  2501:   ncom=n; 
                   2502:   pcom=vector(1,n); 
                   2503:   xicom=vector(1,n); 
                   2504:   nrfunc=func; 
                   2505:   for (j=1;j<=n;j++) { 
                   2506:     pcom[j]=p[j]; 
1.202     brouard  2507:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2508:   } 
1.187     brouard  2509: 
1.203     brouard  2510: #ifdef LINMINORIGINAL
                   2511:   xx=1.;
                   2512: #else
                   2513:   axs=0.0;
                   2514:   xxs=1.;
                   2515:   do{
                   2516:     xx= xxs;
                   2517: #endif
1.187     brouard  2518:     ax=0.;
                   2519:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2520:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2521:     /* 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))   */
                   2522:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2523:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2524:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2525:     /* 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  2526: #ifdef LINMINORIGINAL
                   2527: #else
                   2528:     if (fx != fx){
1.224     brouard  2529:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2530:                        printf("|");
                   2531:                        fprintf(ficlog,"|");
1.203     brouard  2532: #ifdef DEBUGLINMIN
1.224     brouard  2533:                        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  2534: #endif
                   2535:     }
1.224     brouard  2536:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2537: #endif
                   2538:   
1.191     brouard  2539: #ifdef DEBUGLINMIN
                   2540:   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  2541:   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  2542: #endif
1.224     brouard  2543: #ifdef LINMINORIGINAL
                   2544: #else
1.317     brouard  2545:   if(fb == fx){ /* Flat function in the direction */
                   2546:     xmin=xx;
1.224     brouard  2547:     *flat=1;
1.317     brouard  2548:   }else{
1.224     brouard  2549:     *flat=0;
                   2550: #endif
                   2551:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2552:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2553:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2554:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2555:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2556:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2557: #ifdef DEBUG
1.224     brouard  2558:   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);
                   2559:   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);
                   2560: #endif
                   2561: #ifdef LINMINORIGINAL
                   2562: #else
                   2563:                        }
1.126     brouard  2564: #endif
1.191     brouard  2565: #ifdef DEBUGLINMIN
                   2566:   printf("linmin end ");
1.202     brouard  2567:   fprintf(ficlog,"linmin end ");
1.191     brouard  2568: #endif
1.126     brouard  2569:   for (j=1;j<=n;j++) { 
1.203     brouard  2570: #ifdef LINMINORIGINAL
                   2571:     xi[j] *= xmin; 
                   2572: #else
                   2573: #ifdef DEBUGLINMIN
                   2574:     if(xxs <1.0)
                   2575:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2576: #endif
                   2577:     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) */
                   2578: #ifdef DEBUGLINMIN
                   2579:     if(xxs <1.0)
                   2580:       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 );
                   2581: #endif
                   2582: #endif
1.187     brouard  2583:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2584:   } 
1.191     brouard  2585: #ifdef DEBUGLINMIN
1.203     brouard  2586:   printf("\n");
1.191     brouard  2587:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2588:   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  2589:   for (j=1;j<=n;j++) { 
1.202     brouard  2590:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2591:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2592:     if(j % ncovmodel == 0){
1.191     brouard  2593:       printf("\n");
1.202     brouard  2594:       fprintf(ficlog,"\n");
                   2595:     }
1.191     brouard  2596:   }
1.203     brouard  2597: #else
1.191     brouard  2598: #endif
1.126     brouard  2599:   free_vector(xicom,1,n); 
                   2600:   free_vector(pcom,1,n); 
                   2601: } 
                   2602: 
                   2603: 
                   2604: /*************** powell ************************/
1.162     brouard  2605: /*
1.317     brouard  2606: Minimization of a function func of n variables. Input consists in an initial starting point
                   2607: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2608: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2609: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2610: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2611: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2612:  */
1.224     brouard  2613: #ifdef LINMINORIGINAL
                   2614: #else
                   2615:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2616:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2617: #endif
1.126     brouard  2618: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2619:            double (*func)(double [])) 
                   2620: { 
1.224     brouard  2621: #ifdef LINMINORIGINAL
                   2622:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2623:              double (*func)(double [])); 
1.224     brouard  2624: #else 
1.241     brouard  2625:  void linmin(double p[], double xi[], int n, double *fret,
                   2626:             double (*func)(double []),int *flat); 
1.224     brouard  2627: #endif
1.239     brouard  2628:  int i,ibig,j,jk,k; 
1.126     brouard  2629:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2630:   double directest;
1.126     brouard  2631:   double fp,fptt;
                   2632:   double *xits;
                   2633:   int niterf, itmp;
1.349     brouard  2634:   int Bigter=0, nBigterf=1;
                   2635:   
1.126     brouard  2636:   pt=vector(1,n); 
                   2637:   ptt=vector(1,n); 
                   2638:   xit=vector(1,n); 
                   2639:   xits=vector(1,n); 
                   2640:   *fret=(*func)(p); 
                   2641:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2642:   rcurr_time = time(NULL);
                   2643:   fp=(*fret); /* Initialisation */
1.126     brouard  2644:   for (*iter=1;;++(*iter)) { 
                   2645:     ibig=0; 
                   2646:     del=0.0; 
1.157     brouard  2647:     rlast_time=rcurr_time;
1.349     brouard  2648:     rlast_btime=rcurr_time;
1.157     brouard  2649:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2650:     rcurr_time = time(NULL);  
                   2651:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2652:     /* 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); */
                   2653:     /* 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  2654:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2655:     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);
                   2656:     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);
                   2657:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2658:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2659:     for (i=1;i<=n;i++) {
1.126     brouard  2660:       fprintf(ficrespow," %.12lf", p[i]);
                   2661:     }
1.239     brouard  2662:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2663:     printf("\n#model=  1      +     age ");
                   2664:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2665:     if(nagesqr==1){
1.241     brouard  2666:        printf("  + age*age  ");
                   2667:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2668:     }
                   2669:     for(j=1;j <=ncovmodel-2;j++){
                   2670:       if(Typevar[j]==0) {
                   2671:        printf("  +      V%d  ",Tvar[j]);
                   2672:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2673:       }else if(Typevar[j]==1) {
                   2674:        printf("  +    V%d*age ",Tvar[j]);
                   2675:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2676:       }else if(Typevar[j]==2) {
                   2677:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2678:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2679:       }else if(Typevar[j]==3) {
                   2680:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2681:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2682:       }
                   2683:     }
1.126     brouard  2684:     printf("\n");
1.239     brouard  2685: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2686: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2687:     fprintf(ficlog,"\n");
1.239     brouard  2688:     for(i=1,jk=1; i <=nlstate; i++){
                   2689:       for(k=1; k <=(nlstate+ndeath); k++){
                   2690:        if (k != i) {
                   2691:          printf("%d%d ",i,k);
                   2692:          fprintf(ficlog,"%d%d ",i,k);
                   2693:          for(j=1; j <=ncovmodel; j++){
                   2694:            printf("%12.7f ",p[jk]);
                   2695:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2696:            jk++; 
                   2697:          }
                   2698:          printf("\n");
                   2699:          fprintf(ficlog,"\n");
                   2700:        }
                   2701:       }
                   2702:     }
1.241     brouard  2703:     if(*iter <=3 && *iter >1){
1.157     brouard  2704:       tml = *localtime(&rcurr_time);
                   2705:       strcpy(strcurr,asctime(&tml));
                   2706:       rforecast_time=rcurr_time; 
1.126     brouard  2707:       itmp = strlen(strcurr);
                   2708:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2709:        strcurr[itmp-1]='\0';
1.162     brouard  2710:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2711:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2712:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2713:        niterf=nBigterf*ncovmodel;
                   2714:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2715:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2716:        forecast_time = *localtime(&rforecast_time);
                   2717:        strcpy(strfor,asctime(&forecast_time));
                   2718:        itmp = strlen(strfor);
                   2719:        if(strfor[itmp-1]=='\n')
                   2720:          strfor[itmp-1]='\0';
1.349     brouard  2721:        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);
                   2722:        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  2723:       }
                   2724:     }
1.187     brouard  2725:     for (i=1;i<=n;i++) { /* For each direction i */
                   2726:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2727:       fptt=(*fret); 
                   2728: #ifdef DEBUG
1.203     brouard  2729:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2730:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2731: #endif
1.203     brouard  2732:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2733:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2734: #ifdef LINMINORIGINAL
1.188     brouard  2735:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2736: #else
                   2737:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2738:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2739: #endif
                   2740:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2741:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2742:                                /* because that direction will be replaced unless the gain del is small */
                   2743:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2744:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2745:                                /* with the new direction. */
                   2746:                                del=fabs(fptt-(*fret)); 
                   2747:                                ibig=i; 
1.126     brouard  2748:       } 
                   2749: #ifdef DEBUG
                   2750:       printf("%d %.12e",i,(*fret));
                   2751:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2752:       for (j=1;j<=n;j++) {
1.224     brouard  2753:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2754:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2755:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2756:       }
                   2757:       for(j=1;j<=n;j++) {
1.225     brouard  2758:                                printf(" p(%d)=%.12e",j,p[j]);
                   2759:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2760:       }
                   2761:       printf("\n");
                   2762:       fprintf(ficlog,"\n");
                   2763: #endif
1.187     brouard  2764:     } /* end loop on each direction i */
                   2765:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2766:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2767:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2768:     for(j=1;j<=n;j++) {
                   2769:       if(flatdir[j] >0){
                   2770:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2771:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2772:       }
1.319     brouard  2773:       /* printf("\n"); */
                   2774:       /* fprintf(ficlog,"\n"); */
                   2775:     }
1.243     brouard  2776:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2777:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2778:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2779:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2780:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2781:       /* decreased of more than 3.84  */
                   2782:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2783:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2784:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2785:                        
1.188     brouard  2786:       /* Starting the program with initial values given by a former maximization will simply change */
                   2787:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2788:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2789:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2790: #ifdef DEBUG
                   2791:       int k[2],l;
                   2792:       k[0]=1;
                   2793:       k[1]=-1;
                   2794:       printf("Max: %.12e",(*func)(p));
                   2795:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2796:       for (j=1;j<=n;j++) {
                   2797:        printf(" %.12e",p[j]);
                   2798:        fprintf(ficlog," %.12e",p[j]);
                   2799:       }
                   2800:       printf("\n");
                   2801:       fprintf(ficlog,"\n");
                   2802:       for(l=0;l<=1;l++) {
                   2803:        for (j=1;j<=n;j++) {
                   2804:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2805:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2806:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2807:        }
                   2808:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2809:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2810:       }
                   2811: #endif
                   2812: 
                   2813:       free_vector(xit,1,n); 
                   2814:       free_vector(xits,1,n); 
                   2815:       free_vector(ptt,1,n); 
                   2816:       free_vector(pt,1,n); 
                   2817:       return; 
1.192     brouard  2818:     } /* enough precision */ 
1.240     brouard  2819:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2820:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2821:       ptt[j]=2.0*p[j]-pt[j]; 
                   2822:       xit[j]=p[j]-pt[j]; 
                   2823:       pt[j]=p[j]; 
                   2824:     } 
1.181     brouard  2825:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2826: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2827:                if (*iter <=4) {
1.225     brouard  2828: #else
                   2829: #endif
1.224     brouard  2830: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2831: #else
1.161     brouard  2832:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2833: #endif
1.162     brouard  2834:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2835:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2836:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2837:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2838:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2839:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2840:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2841:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2842:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2843:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2844:       /* mu² and del² are equal when f3=f1 */
                   2845:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2846:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2847:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2848:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2849: #ifdef NRCORIGINAL
                   2850:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2851: #else
                   2852:       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  2853:       t= t- del*SQR(fp-fptt);
1.183     brouard  2854: #endif
1.202     brouard  2855:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2856: #ifdef DEBUG
1.181     brouard  2857:       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);
                   2858:       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  2859:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2860:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2861:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2862:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2863:       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);
                   2864:       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);
                   2865: #endif
1.183     brouard  2866: #ifdef POWELLORIGINAL
                   2867:       if (t < 0.0) { /* Then we use it for new direction */
                   2868: #else
1.182     brouard  2869:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2870:                                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  2871:         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  2872:         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  2873:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2874:       } 
1.181     brouard  2875:       if (directest < 0.0) { /* Then we use it for new direction */
                   2876: #endif
1.191     brouard  2877: #ifdef DEBUGLINMIN
1.234     brouard  2878:        printf("Before linmin in direction P%d-P0\n",n);
                   2879:        for (j=1;j<=n;j++) {
                   2880:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2881:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2882:          if(j % ncovmodel == 0){
                   2883:            printf("\n");
                   2884:            fprintf(ficlog,"\n");
                   2885:          }
                   2886:        }
1.224     brouard  2887: #endif
                   2888: #ifdef LINMINORIGINAL
1.234     brouard  2889:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2890: #else
1.234     brouard  2891:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2892:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2893: #endif
1.234     brouard  2894:        
1.191     brouard  2895: #ifdef DEBUGLINMIN
1.234     brouard  2896:        for (j=1;j<=n;j++) { 
                   2897:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2898:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2899:          if(j % ncovmodel == 0){
                   2900:            printf("\n");
                   2901:            fprintf(ficlog,"\n");
                   2902:          }
                   2903:        }
1.224     brouard  2904: #endif
1.234     brouard  2905:        for (j=1;j<=n;j++) { 
                   2906:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2907:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2908:        }
1.224     brouard  2909: #ifdef LINMINORIGINAL
                   2910: #else
1.234     brouard  2911:        for (j=1, flatd=0;j<=n;j++) {
                   2912:          if(flatdir[j]>0)
                   2913:            flatd++;
                   2914:        }
                   2915:        if(flatd >0){
1.255     brouard  2916:          printf("%d flat directions: ",flatd);
                   2917:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2918:          for (j=1;j<=n;j++) { 
                   2919:            if(flatdir[j]>0){
                   2920:              printf("%d ",j);
                   2921:              fprintf(ficlog,"%d ",j);
                   2922:            }
                   2923:          }
                   2924:          printf("\n");
                   2925:          fprintf(ficlog,"\n");
1.319     brouard  2926: #ifdef FLATSUP
                   2927:           free_vector(xit,1,n); 
                   2928:           free_vector(xits,1,n); 
                   2929:           free_vector(ptt,1,n); 
                   2930:           free_vector(pt,1,n); 
                   2931:           return;
                   2932: #endif
1.234     brouard  2933:        }
1.191     brouard  2934: #endif
1.234     brouard  2935:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2936:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2937:        
1.126     brouard  2938: #ifdef DEBUG
1.234     brouard  2939:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2940:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2941:        for(j=1;j<=n;j++){
                   2942:          printf(" %lf",xit[j]);
                   2943:          fprintf(ficlog," %lf",xit[j]);
                   2944:        }
                   2945:        printf("\n");
                   2946:        fprintf(ficlog,"\n");
1.126     brouard  2947: #endif
1.192     brouard  2948:       } /* end of t or directest negative */
1.224     brouard  2949: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2950: #else
1.234     brouard  2951:       } /* end if (fptt < fp)  */
1.192     brouard  2952: #endif
1.225     brouard  2953: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2954:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2955: #else
1.224     brouard  2956: #endif
1.234     brouard  2957:                } /* loop iteration */ 
1.126     brouard  2958: } 
1.234     brouard  2959:   
1.126     brouard  2960: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2961:   
1.235     brouard  2962:   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  2963:   {
1.338     brouard  2964:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2965:      *   (and selected quantitative values in nres)
                   2966:      *  by left multiplying the unit
                   2967:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2968:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2969:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2970:      * or prevalence in state 1, prevalence in state 2, 0
                   2971:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2972:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2973:      * Output is prlim.
                   2974:      * Initial matrix pimij 
                   2975:      */
1.206     brouard  2976:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2977:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2978:   /*  0,                   0                  , 1} */
                   2979:   /*
                   2980:    * and after some iteration: */
                   2981:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2982:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2983:   /*  0,                   0                  , 1} */
                   2984:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2985:   /* {0.51571254859325999, 0.4842874514067399, */
                   2986:   /*  0.51326036147820708, 0.48673963852179264} */
                   2987:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2988:     
1.332     brouard  2989:     int i, ii,j,k, k1;
1.209     brouard  2990:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2991:   /* double **matprod2(); */ /* test */
1.218     brouard  2992:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2993:   double **newm;
1.209     brouard  2994:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2995:   int ncvloop=0;
1.288     brouard  2996:   int first=0;
1.169     brouard  2997:   
1.209     brouard  2998:   min=vector(1,nlstate);
                   2999:   max=vector(1,nlstate);
                   3000:   meandiff=vector(1,nlstate);
                   3001: 
1.218     brouard  3002:        /* Starting with matrix unity */
1.126     brouard  3003:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3004:     for (j=1;j<=nlstate+ndeath;j++){
                   3005:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3006:     }
1.169     brouard  3007:   
                   3008:   cov[1]=1.;
                   3009:   
                   3010:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3011:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3012:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3013:     ncvloop++;
1.126     brouard  3014:     newm=savm;
                   3015:     /* Covariates have to be included here again */
1.138     brouard  3016:     cov[2]=agefin;
1.319     brouard  3017:      if(nagesqr==1){
                   3018:       cov[3]= agefin*agefin;
                   3019:      }
1.332     brouard  3020:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3021:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3022:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3023:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3024:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3025:        }else{
                   3026:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3027:        }
                   3028:      }/* End of loop on model equation */
                   3029:      
                   3030: /* Start of old code (replaced by a loop on position in the model equation */
                   3031:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3032:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3033:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3034:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3035:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3036:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3037:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3038:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3039:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3040:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3041:     /*    *nsd=3                              (1)  (2)           (3) */
                   3042:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3043:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3044:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3045:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3046:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3047:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3048:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3049:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3050:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3051:     /*    *TvarsDpType */
                   3052:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3053:     /*    * nsd=1              (1)           (2) */
                   3054:     /*    *TvarsD[nsd]          3             2 */
                   3055:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3056:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3057:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3058:     /*    *\/ */
                   3059:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3060:     /*   /\* 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)); *\/ */
                   3061:     /* } */
                   3062:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3063:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3064:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3065:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3066:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3067:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3068:     /*   /\* 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]); *\/ */
                   3069:     /* } */
                   3070:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3071:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3072:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3073:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3074:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3075:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3076:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3077:     /*   } */
                   3078:     /*   /\* 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]); *\/ */
                   3079:     /* } */
                   3080:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3081:     /*   /\* 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]); *\/ */
                   3082:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3083:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3084:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3085:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3086:     /*         }else{ */
                   3087:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3088:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3089:     /*         } */
                   3090:     /*   }else{ */
                   3091:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3092:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3093:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3094:     /*         }else{ */
                   3095:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3096:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3097:     /*         } */
                   3098:     /*   } */
                   3099:     /* } /\* End product without age *\/ */
                   3100: /* ENd of old code */
1.138     brouard  3101:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3102:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3103:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3104:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3105:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3106:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3107:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3108:     
1.126     brouard  3109:     savm=oldm;
                   3110:     oldm=newm;
1.209     brouard  3111: 
                   3112:     for(j=1; j<=nlstate; j++){
                   3113:       max[j]=0.;
                   3114:       min[j]=1.;
                   3115:     }
                   3116:     for(i=1;i<=nlstate;i++){
                   3117:       sumnew=0;
                   3118:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3119:       for(j=1; j<=nlstate; j++){ 
                   3120:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3121:        max[j]=FMAX(max[j],prlim[i][j]);
                   3122:        min[j]=FMIN(min[j],prlim[i][j]);
                   3123:       }
                   3124:     }
                   3125: 
1.126     brouard  3126:     maxmax=0.;
1.209     brouard  3127:     for(j=1; j<=nlstate; j++){
                   3128:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3129:       maxmax=FMAX(maxmax,meandiff[j]);
                   3130:       /* 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  3131:     } /* j loop */
1.203     brouard  3132:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3133:     /* 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  3134:     if(maxmax < ftolpl){
1.209     brouard  3135:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3136:       free_vector(min,1,nlstate);
                   3137:       free_vector(max,1,nlstate);
                   3138:       free_vector(meandiff,1,nlstate);
1.126     brouard  3139:       return prlim;
                   3140:     }
1.288     brouard  3141:   } /* agefin loop */
1.208     brouard  3142:     /* After some age loop it doesn't converge */
1.288     brouard  3143:   if(!first){
                   3144:     first=1;
                   3145:     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  3146:     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);
                   3147:   }else if (first >=1 && first <10){
                   3148:     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);
                   3149:     first++;
                   3150:   }else if (first ==10){
                   3151:     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);
                   3152:     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");
                   3153:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3154:     first++;
1.288     brouard  3155:   }
                   3156: 
1.209     brouard  3157:   /* 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); */
                   3158:   free_vector(min,1,nlstate);
                   3159:   free_vector(max,1,nlstate);
                   3160:   free_vector(meandiff,1,nlstate);
1.208     brouard  3161:   
1.169     brouard  3162:   return prlim; /* should not reach here */
1.126     brouard  3163: }
                   3164: 
1.217     brouard  3165: 
                   3166:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3167: 
1.218     brouard  3168:  /* 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) */
                   3169:  /* 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  3170:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3171: {
1.264     brouard  3172:   /* 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  3173:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3174:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3175:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3176:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3177:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3178:   /* Initial matrix pimij */
                   3179:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3180:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3181:   /*  0,                   0                  , 1} */
                   3182:   /*
                   3183:    * and after some iteration: */
                   3184:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3185:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3186:   /*  0,                   0                  , 1} */
                   3187:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3188:   /* {0.51571254859325999, 0.4842874514067399, */
                   3189:   /*  0.51326036147820708, 0.48673963852179264} */
                   3190:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3191: 
1.332     brouard  3192:   int i, ii,j,k, k1;
1.247     brouard  3193:   int first=0;
1.217     brouard  3194:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3195:   /* double **matprod2(); */ /* test */
                   3196:   double **out, cov[NCOVMAX+1], **bmij();
                   3197:   double **newm;
1.218     brouard  3198:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3199:   double        **oldm, **savm;  /* for use */
                   3200: 
1.217     brouard  3201:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3202:   int ncvloop=0;
                   3203:   
                   3204:   min=vector(1,nlstate);
                   3205:   max=vector(1,nlstate);
                   3206:   meandiff=vector(1,nlstate);
                   3207: 
1.266     brouard  3208:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3209:   oldm=oldms; savm=savms;
                   3210:   
                   3211:   /* Starting with matrix unity */
                   3212:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3213:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3214:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3215:     }
                   3216:   
                   3217:   cov[1]=1.;
                   3218:   
                   3219:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3220:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3221:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3222:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3223:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3224:     ncvloop++;
1.218     brouard  3225:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3226:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3227:     /* Covariates have to be included here again */
                   3228:     cov[2]=agefin;
1.319     brouard  3229:     if(nagesqr==1){
1.217     brouard  3230:       cov[3]= agefin*agefin;;
1.319     brouard  3231:     }
1.332     brouard  3232:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3233:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3234:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3235:       }else{
1.332     brouard  3236:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3237:       }
1.332     brouard  3238:     }/* End of loop on model equation */
                   3239: 
                   3240: /* Old code */ 
                   3241: 
                   3242:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3243:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3244:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3245:     /*   /\* 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)); *\/ */
                   3246:     /* } */
                   3247:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3248:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3249:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3250:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3251:     /* /\* } *\/ */
                   3252:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3253:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3254:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3255:     /*   /\* 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]); *\/ */
                   3256:     /* } */
                   3257:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3258:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3259:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3260:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3261:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3262:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3263:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3264:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3265:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3266:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3267:     /*   } */
                   3268:     /*   /\* 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]); *\/ */
                   3269:     /* } */
                   3270:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3271:     /*   /\* 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]); *\/ */
                   3272:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3273:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3274:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3275:     /*         }else{ */
                   3276:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3277:     /*         } */
                   3278:     /*   }else{ */
                   3279:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3280:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3281:     /*         }else{ */
                   3282:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3283:     /*         } */
                   3284:     /*   } */
                   3285:     /* } */
1.217     brouard  3286:     
                   3287:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3288:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3289:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3290:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3291:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3292:                /* ij should be linked to the correct index of cov */
                   3293:                /* age and covariate values ij are in 'cov', but we need to pass
                   3294:                 * ij for the observed prevalence at age and status and covariate
                   3295:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3296:                 */
                   3297:     /* 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 *\/ */
                   3298:     /* 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 *\/ */
                   3299:     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  3300:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3301:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3302:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3303:     /*         printf("%d newm= ",i); */
                   3304:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3305:     /*           printf("%f ",newm[i][j]); */
                   3306:     /*         } */
                   3307:     /*         printf("oldm * "); */
                   3308:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3309:     /*           printf("%f ",oldm[i][j]); */
                   3310:     /*         } */
1.268     brouard  3311:     /*         printf(" bmmij "); */
1.266     brouard  3312:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3313:     /*           printf("%f ",pmmij[i][j]); */
                   3314:     /*         } */
                   3315:     /*         printf("\n"); */
                   3316:     /*   } */
                   3317:     /* } */
1.217     brouard  3318:     savm=oldm;
                   3319:     oldm=newm;
1.266     brouard  3320: 
1.217     brouard  3321:     for(j=1; j<=nlstate; j++){
                   3322:       max[j]=0.;
                   3323:       min[j]=1.;
                   3324:     }
                   3325:     for(j=1; j<=nlstate; j++){ 
                   3326:       for(i=1;i<=nlstate;i++){
1.234     brouard  3327:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3328:        bprlim[i][j]= newm[i][j];
                   3329:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3330:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3331:       }
                   3332:     }
1.218     brouard  3333:                
1.217     brouard  3334:     maxmax=0.;
                   3335:     for(i=1; i<=nlstate; i++){
1.318     brouard  3336:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3337:       maxmax=FMAX(maxmax,meandiff[i]);
                   3338:       /* 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  3339:     } /* i loop */
1.217     brouard  3340:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3341:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3342:     if(maxmax < ftolpl){
1.220     brouard  3343:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3344:       free_vector(min,1,nlstate);
                   3345:       free_vector(max,1,nlstate);
                   3346:       free_vector(meandiff,1,nlstate);
                   3347:       return bprlim;
                   3348:     }
1.288     brouard  3349:   } /* agefin loop */
1.217     brouard  3350:     /* After some age loop it doesn't converge */
1.288     brouard  3351:   if(!first){
1.247     brouard  3352:     first=1;
                   3353:     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\
                   3354: 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);
                   3355:   }
                   3356:   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  3357: 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);
                   3358:   /* 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); */
                   3359:   free_vector(min,1,nlstate);
                   3360:   free_vector(max,1,nlstate);
                   3361:   free_vector(meandiff,1,nlstate);
                   3362:   
                   3363:   return bprlim; /* should not reach here */
                   3364: }
                   3365: 
1.126     brouard  3366: /*************** transition probabilities ***************/ 
                   3367: 
                   3368: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3369: {
1.138     brouard  3370:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3371:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3372:      model to the ncovmodel covariates (including constant and age).
                   3373:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3374:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3375:      ncth covariate in the global vector x is given by the formula:
                   3376:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3377:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3378:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3379:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3380:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3381:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3382:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3383:   */
                   3384:   double s1, lnpijopii;
1.126     brouard  3385:   /*double t34;*/
1.164     brouard  3386:   int i,j, nc, ii, jj;
1.126     brouard  3387: 
1.223     brouard  3388:   for(i=1; i<= nlstate; i++){
                   3389:     for(j=1; j<i;j++){
                   3390:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3391:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3392:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3393:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3394:       }
                   3395:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3396:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3397:     }
                   3398:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3399:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3400:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3401:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3402:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3403:       }
                   3404:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3405:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3406:     }
                   3407:   }
1.218     brouard  3408:   
1.223     brouard  3409:   for(i=1; i<= nlstate; i++){
                   3410:     s1=0;
                   3411:     for(j=1; j<i; j++){
1.339     brouard  3412:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3413:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3414:     }
                   3415:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3416:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3417:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3418:     }
                   3419:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3420:     ps[i][i]=1./(s1+1.);
                   3421:     /* Computing other pijs */
                   3422:     for(j=1; j<i; j++)
1.325     brouard  3423:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3424:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3425:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3426:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3427:   } /* end i */
1.218     brouard  3428:   
1.223     brouard  3429:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3430:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3431:       ps[ii][jj]=0;
                   3432:       ps[ii][ii]=1;
                   3433:     }
                   3434:   }
1.294     brouard  3435: 
                   3436: 
1.223     brouard  3437:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3438:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3439:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3440:   /*   } */
                   3441:   /*   printf("\n "); */
                   3442:   /* } */
                   3443:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3444:   /*
                   3445:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3446:                goto end;*/
1.266     brouard  3447:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3448: }
                   3449: 
1.218     brouard  3450: /*************** backward transition probabilities ***************/ 
                   3451: 
                   3452:  /* 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 ) */
                   3453: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3454:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3455: {
1.302     brouard  3456:   /* 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  3457:    * 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  3458:    */
1.218     brouard  3459:   int i, ii, j,k;
1.222     brouard  3460:   
                   3461:   double **out, **pmij();
                   3462:   double sumnew=0.;
1.218     brouard  3463:   double agefin;
1.292     brouard  3464:   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  3465:   double **dnewm, **dsavm, **doldm;
                   3466:   double **bbmij;
                   3467:   
1.218     brouard  3468:   doldm=ddoldms; /* global pointers */
1.222     brouard  3469:   dnewm=ddnewms;
                   3470:   dsavm=ddsavms;
1.318     brouard  3471: 
                   3472:   /* Debug */
                   3473:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3474:   agefin=cov[2];
1.268     brouard  3475:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3476:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3477:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3478:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3479: 
                   3480:   /* P_x */
1.325     brouard  3481:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3482:   /* outputs pmmij which is a stochastic matrix in row */
                   3483: 
                   3484:   /* Diag(w_x) */
1.292     brouard  3485:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3486:   sumnew=0.;
1.269     brouard  3487:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3488:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3489:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3490:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3491:   }
                   3492:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3493:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3494:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3495:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3496:     }
                   3497:   }else{
                   3498:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3499:       for (j=1;j<=nlstate+ndeath;j++)
                   3500:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3501:     }
                   3502:     /* if(sumnew <0.9){ */
                   3503:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3504:     /* } */
                   3505:   }
                   3506:   k3=0.0;  /* We put the last diagonal to 0 */
                   3507:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3508:       doldm[ii][ii]= k3;
                   3509:   }
                   3510:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3511:   
1.292     brouard  3512:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3513:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3514: 
1.292     brouard  3515:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3516:   /* 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  3517:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3518:     sumnew=0.;
1.222     brouard  3519:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3520:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3521:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3522:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3523:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3524:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3525:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3526:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3527:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3528:        /* }else */
1.268     brouard  3529:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3530:     } /*End ii */
                   3531:   } /* 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 */
                   3532: 
1.292     brouard  3533:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3534:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3535:   /* end bmij */
1.266     brouard  3536:   return ps; /*pointer is unchanged */
1.218     brouard  3537: }
1.217     brouard  3538: /*************** transition probabilities ***************/ 
                   3539: 
1.218     brouard  3540: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3541: {
                   3542:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3543:      computes the probability to be observed in state j being in state i by appying the
                   3544:      model to the ncovmodel covariates (including constant and age).
                   3545:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3546:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3547:      ncth covariate in the global vector x is given by the formula:
                   3548:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3549:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3550:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3551:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3552:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3553:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3554:   */
                   3555:   double s1, lnpijopii;
                   3556:   /*double t34;*/
                   3557:   int i,j, nc, ii, jj;
                   3558: 
1.234     brouard  3559:   for(i=1; i<= nlstate; i++){
                   3560:     for(j=1; j<i;j++){
                   3561:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3562:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3563:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3564:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3565:       }
                   3566:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3567:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3568:     }
                   3569:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3570:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3571:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3572:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3573:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3574:       }
                   3575:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3576:     }
                   3577:   }
                   3578:   
                   3579:   for(i=1; i<= nlstate; i++){
                   3580:     s1=0;
                   3581:     for(j=1; j<i; j++){
                   3582:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3583:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3584:     }
                   3585:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3586:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3587:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3588:     }
                   3589:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3590:     ps[i][i]=1./(s1+1.);
                   3591:     /* Computing other pijs */
                   3592:     for(j=1; j<i; j++)
                   3593:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3594:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3595:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3596:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3597:   } /* end i */
                   3598:   
                   3599:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3600:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3601:       ps[ii][jj]=0;
                   3602:       ps[ii][ii]=1;
                   3603:     }
                   3604:   }
1.296     brouard  3605:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3606:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3607:     s1=0.;
                   3608:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3609:       s1+=ps[ii][jj];
                   3610:     }
                   3611:     for(ii=1; ii<= nlstate; ii++){
                   3612:       ps[ii][jj]=ps[ii][jj]/s1;
                   3613:     }
                   3614:   }
                   3615:   /* Transposition */
                   3616:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3617:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3618:       s1=ps[ii][jj];
                   3619:       ps[ii][jj]=ps[jj][ii];
                   3620:       ps[jj][ii]=s1;
                   3621:     }
                   3622:   }
                   3623:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3624:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3625:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3626:   /*   } */
                   3627:   /*   printf("\n "); */
                   3628:   /* } */
                   3629:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3630:   /*
                   3631:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3632:     goto end;*/
                   3633:   return ps;
1.217     brouard  3634: }
                   3635: 
                   3636: 
1.126     brouard  3637: /**************** Product of 2 matrices ******************/
                   3638: 
1.145     brouard  3639: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3640: {
                   3641:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3642:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3643:   /* in, b, out are matrice of pointers which should have been initialized 
                   3644:      before: only the contents of out is modified. The function returns
                   3645:      a pointer to pointers identical to out */
1.145     brouard  3646:   int i, j, k;
1.126     brouard  3647:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3648:     for(k=ncolol; k<=ncoloh; k++){
                   3649:       out[i][k]=0.;
                   3650:       for(j=ncl; j<=nch; j++)
                   3651:        out[i][k] +=in[i][j]*b[j][k];
                   3652:     }
1.126     brouard  3653:   return out;
                   3654: }
                   3655: 
                   3656: 
                   3657: /************* Higher Matrix Product ***************/
                   3658: 
1.235     brouard  3659: 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  3660: {
1.336     brouard  3661:   /* Already optimized with precov.
                   3662:      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  3663:      'nhstepm*hstepm*stepm' months (i.e. until
                   3664:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3665:      nhstepm*hstepm matrices. 
                   3666:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3667:      (typically every 2 years instead of every month which is too big 
                   3668:      for the memory).
                   3669:      Model is determined by parameters x and covariates have to be 
                   3670:      included manually here. 
                   3671: 
                   3672:      */
                   3673: 
1.330     brouard  3674:   int i, j, d, h, k, k1;
1.131     brouard  3675:   double **out, cov[NCOVMAX+1];
1.126     brouard  3676:   double **newm;
1.187     brouard  3677:   double agexact;
1.214     brouard  3678:   double agebegin, ageend;
1.126     brouard  3679: 
                   3680:   /* Hstepm could be zero and should return the unit matrix */
                   3681:   for (i=1;i<=nlstate+ndeath;i++)
                   3682:     for (j=1;j<=nlstate+ndeath;j++){
                   3683:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3684:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3685:     }
                   3686:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3687:   for(h=1; h <=nhstepm; h++){
                   3688:     for(d=1; d <=hstepm; d++){
                   3689:       newm=savm;
                   3690:       /* Covariates have to be included here again */
                   3691:       cov[1]=1.;
1.214     brouard  3692:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3693:       cov[2]=agexact;
1.319     brouard  3694:       if(nagesqr==1){
1.227     brouard  3695:        cov[3]= agexact*agexact;
1.319     brouard  3696:       }
1.330     brouard  3697:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3698:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3699:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3700:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3701:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3702:        }else{
                   3703:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3704:        }
                   3705:       }/* End of loop on model equation */
                   3706:        /* Old code */ 
                   3707: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3708: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3709: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3710: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3711: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3712: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3713: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3714: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3715: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3716: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3717: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3718: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3719: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3720: /*       /\* 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]])); *\/ */
                   3721: /*       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); */
                   3722: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3723: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3724: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3725: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3726: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3727: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3728: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3729: /*       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]]); */
                   3730: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3731: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3732: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3733: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3734: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3735: /*       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]); */
                   3736: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3737: 
                   3738: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3739: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3740: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3741: /*       /\* *\/ */
1.330     brouard  3742: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3743: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3744: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3745: /* /\*cptcovage=2                   1               2      *\/ */
                   3746: /* /\*Tage[k]=                      5               8      *\/  */
                   3747: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3748: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3749: /*       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]]); */
                   3750: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3751: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3752: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3753: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3754: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3755: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3756: /*       /\*   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); *\/ */
                   3757: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3758: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3759: /*       /\* } *\/ */
                   3760: /*       /\* 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]); *\/ */
                   3761: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3762: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3763: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3764: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3765: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3766: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3767: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3768: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3769: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3770:          
1.332     brouard  3771: /*       /\* 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])]); *\/ */
                   3772: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3773: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3774: /*       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]]); */
                   3775: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3776: 
                   3777: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3778: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3779: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3780: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3781: /*           /\* 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]])]; *\/ */
                   3782: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3783: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3784: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3785: /*       /\*   } *\/ */
                   3786: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3787: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3788: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3789: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3790: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3791: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3792: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3793: /*       /\*   } *\/ */
                   3794: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3795: /*     }/\*end of products *\/ */
                   3796:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3797:       /* for (k=1; k<=cptcovn;k++)  */
                   3798:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3799:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3800:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3801:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3802:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3803:       
                   3804:       
1.126     brouard  3805:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3806:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3807:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3808:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3809:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3810:       /* if((int)age == 70){ */
                   3811:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3812:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3813:       /*         printf("%d pmmij ",i); */
                   3814:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3815:       /*           printf("%f ",pmmij[i][j]); */
                   3816:       /*         } */
                   3817:       /*         printf(" oldm "); */
                   3818:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3819:       /*           printf("%f ",oldm[i][j]); */
                   3820:       /*         } */
                   3821:       /*         printf("\n"); */
                   3822:       /*       } */
                   3823:       /* } */
1.126     brouard  3824:       savm=oldm;
                   3825:       oldm=newm;
                   3826:     }
                   3827:     for(i=1; i<=nlstate+ndeath; i++)
                   3828:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3829:        po[i][j][h]=newm[i][j];
                   3830:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3831:       }
1.128     brouard  3832:     /*printf("h=%d ",h);*/
1.126     brouard  3833:   } /* end h */
1.267     brouard  3834:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3835:   return po;
                   3836: }
                   3837: 
1.217     brouard  3838: /************* Higher Back Matrix Product ***************/
1.218     brouard  3839: /* 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  3840: 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  3841: {
1.332     brouard  3842:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3843:      computes the transition matrix starting at age 'age' over
1.217     brouard  3844:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3845:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3846:      nhstepm*hstepm matrices.
                   3847:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3848:      (typically every 2 years instead of every month which is too big
1.217     brouard  3849:      for the memory).
1.218     brouard  3850:      Model is determined by parameters x and covariates have to be
1.266     brouard  3851:      included manually here. Then we use a call to bmij(x and cov)
                   3852:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3853:   */
1.217     brouard  3854: 
1.332     brouard  3855:   int i, j, d, h, k, k1;
1.266     brouard  3856:   double **out, cov[NCOVMAX+1], **bmij();
                   3857:   double **newm, ***newmm;
1.217     brouard  3858:   double agexact;
                   3859:   double agebegin, ageend;
1.222     brouard  3860:   double **oldm, **savm;
1.217     brouard  3861: 
1.266     brouard  3862:   newmm=po; /* To be saved */
                   3863:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3864:   /* Hstepm could be zero and should return the unit matrix */
                   3865:   for (i=1;i<=nlstate+ndeath;i++)
                   3866:     for (j=1;j<=nlstate+ndeath;j++){
                   3867:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3868:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3869:     }
                   3870:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3871:   for(h=1; h <=nhstepm; h++){
                   3872:     for(d=1; d <=hstepm; d++){
                   3873:       newm=savm;
                   3874:       /* Covariates have to be included here again */
                   3875:       cov[1]=1.;
1.271     brouard  3876:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3877:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3878:         /* Debug */
                   3879:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3880:       cov[2]=agexact;
1.332     brouard  3881:       if(nagesqr==1){
1.222     brouard  3882:        cov[3]= agexact*agexact;
1.332     brouard  3883:       }
                   3884:       /** New code */
                   3885:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3886:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3887:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3888:        }else{
1.332     brouard  3889:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3890:        }
1.332     brouard  3891:       }/* End of loop on model equation */
                   3892:       /** End of new code */
                   3893:   /** This was old code */
                   3894:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3895:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3896:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3897:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3898:       /*   /\* 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)); *\/ */
                   3899:       /* } */
                   3900:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3901:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3902:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3903:       /*       /\* 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]); *\/ */
                   3904:       /* } */
                   3905:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3906:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3907:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3908:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3909:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3910:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3911:       /*       } */
                   3912:       /*       /\* 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]); *\/ */
                   3913:       /* } */
                   3914:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3915:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3916:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3917:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3918:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3919:       /*         }else{ */
                   3920:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3921:       /*         } */
                   3922:       /*       }else{ */
                   3923:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3924:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3925:       /*         }else{ */
                   3926:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3927:       /*         } */
                   3928:       /*       } */
                   3929:       /* }                      */
                   3930:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3931:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3932: /** End of old code */
                   3933:       
1.218     brouard  3934:       /* Careful transposed matrix */
1.266     brouard  3935:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3936:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3937:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3938:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3939:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3940:       /* if((int)age == 70){ */
                   3941:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3942:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3943:       /*         printf("%d pmmij ",i); */
                   3944:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3945:       /*           printf("%f ",pmmij[i][j]); */
                   3946:       /*         } */
                   3947:       /*         printf(" oldm "); */
                   3948:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3949:       /*           printf("%f ",oldm[i][j]); */
                   3950:       /*         } */
                   3951:       /*         printf("\n"); */
                   3952:       /*       } */
                   3953:       /* } */
                   3954:       savm=oldm;
                   3955:       oldm=newm;
                   3956:     }
                   3957:     for(i=1; i<=nlstate+ndeath; i++)
                   3958:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3959:        po[i][j][h]=newm[i][j];
1.268     brouard  3960:        /* if(h==nhstepm) */
                   3961:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3962:       }
1.268     brouard  3963:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3964:   } /* end h */
1.268     brouard  3965:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3966:   return po;
                   3967: }
                   3968: 
                   3969: 
1.162     brouard  3970: #ifdef NLOPT
                   3971:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3972:   double fret;
                   3973:   double *xt;
                   3974:   int j;
                   3975:   myfunc_data *d2 = (myfunc_data *) pd;
                   3976: /* xt = (p1-1); */
                   3977:   xt=vector(1,n); 
                   3978:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3979: 
                   3980:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3981:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3982:   printf("Function = %.12lf ",fret);
                   3983:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3984:   printf("\n");
                   3985:  free_vector(xt,1,n);
                   3986:   return fret;
                   3987: }
                   3988: #endif
1.126     brouard  3989: 
                   3990: /*************** log-likelihood *************/
                   3991: double func( double *x)
                   3992: {
1.336     brouard  3993:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3994:   int ioffset=0;
1.339     brouard  3995:   int ipos=0,iposold=0,ncovv=0;
                   3996: 
1.340     brouard  3997:   double cotvarv, cotvarvold;
1.226     brouard  3998:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3999:   double **out;
                   4000:   double lli; /* Individual log likelihood */
                   4001:   int s1, s2;
1.228     brouard  4002:   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  4003: 
1.226     brouard  4004:   double bbh, survp;
                   4005:   double agexact;
1.336     brouard  4006:   double agebegin, ageend;
1.226     brouard  4007:   /*extern weight */
                   4008:   /* We are differentiating ll according to initial status */
                   4009:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4010:   /*for(i=1;i<imx;i++) 
                   4011:     printf(" %d\n",s[4][i]);
                   4012:   */
1.162     brouard  4013: 
1.226     brouard  4014:   ++countcallfunc;
1.162     brouard  4015: 
1.226     brouard  4016:   cov[1]=1.;
1.126     brouard  4017: 
1.226     brouard  4018:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4019:   ioffset=0;
1.226     brouard  4020:   if(mle==1){
                   4021:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4022:       /* Computes the values of the ncovmodel covariates of the model
                   4023:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4024:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4025:         to be observed in j being in i according to the model.
                   4026:       */
1.243     brouard  4027:       ioffset=2+nagesqr ;
1.233     brouard  4028:    /* Fixed */
1.345     brouard  4029:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4030:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4031:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4032:        /*  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  4033:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4034:        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  4035:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4036:       }
1.226     brouard  4037:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4038:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4039:         has been calculated etc */
                   4040:       /* For an individual i, wav[i] gives the number of effective waves */
                   4041:       /* We compute the contribution to Likelihood of each effective transition
                   4042:         mw[mi][i] is real wave of the mi th effectve wave */
                   4043:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4044:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4045:         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  4046:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4047:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4048:       */
1.336     brouard  4049:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4050:       /* Wave varying (but not age varying) */
1.339     brouard  4051:        /* 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*\/ */
                   4052:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4053:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4054:        /* } */
1.340     brouard  4055:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4056:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4057:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4058:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4059:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4060:          }else{ /* fixed covariate */
1.345     brouard  4061:            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  4062:          }
1.339     brouard  4063:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4064:            cotvarvold=cotvarv;
                   4065:          }else{ /* A second product */
                   4066:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4067:          }
                   4068:          iposold=ipos;
1.340     brouard  4069:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4070:        }
1.339     brouard  4071:        /* for products of time varying to be done */
1.234     brouard  4072:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4073:          for (j=1;j<=nlstate+ndeath;j++){
                   4074:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4075:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4076:          }
1.336     brouard  4077: 
                   4078:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4079:        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  4080:        for(d=0; d<dh[mi][i]; d++){
                   4081:          newm=savm;
                   4082:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4083:          cov[2]=agexact;
                   4084:          if(nagesqr==1)
                   4085:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4086:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4087:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4088:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4089:          /*   else */
                   4090:          /*     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) *\/  */
                   4091:          /* } */
                   4092:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4093:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4094:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4095:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4096:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4097:            }else{ /* fixed covariate */
                   4098:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4099:            }
                   4100:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4101:              cotvarvold=cotvarv;
                   4102:            }else{ /* A second product */
                   4103:              cotvarv=cotvarv*cotvarvold;
                   4104:            }
                   4105:            iposold=ipos;
                   4106:            cov[ioffset+ipos]=cotvarv*agexact;
                   4107:            /* For products */
1.234     brouard  4108:          }
1.349     brouard  4109:          
1.234     brouard  4110:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4111:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4112:          savm=oldm;
                   4113:          oldm=newm;
                   4114:        } /* end mult */
                   4115:        
                   4116:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4117:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4118:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4119:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4120:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4121:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4122:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4123:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4124:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4125:                                 * -stepm/2 to stepm/2 .
                   4126:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4127:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4128:                                 */
1.234     brouard  4129:        s1=s[mw[mi][i]][i];
                   4130:        s2=s[mw[mi+1][i]][i];
                   4131:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4132:        /* bias bh is positive if real duration
                   4133:         * is higher than the multiple of stepm and negative otherwise.
                   4134:         */
                   4135:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4136:        if( s2 > nlstate){ 
                   4137:          /* i.e. if s2 is a death state and if the date of death is known 
                   4138:             then the contribution to the likelihood is the probability to 
                   4139:             die between last step unit time and current  step unit time, 
                   4140:             which is also equal to probability to die before dh 
                   4141:             minus probability to die before dh-stepm . 
                   4142:             In version up to 0.92 likelihood was computed
                   4143:             as if date of death was unknown. Death was treated as any other
                   4144:             health state: the date of the interview describes the actual state
                   4145:             and not the date of a change in health state. The former idea was
                   4146:             to consider that at each interview the state was recorded
                   4147:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4148:             introduced the exact date of death then we should have modified
                   4149:             the contribution of an exact death to the likelihood. This new
                   4150:             contribution is smaller and very dependent of the step unit
                   4151:             stepm. It is no more the probability to die between last interview
                   4152:             and month of death but the probability to survive from last
                   4153:             interview up to one month before death multiplied by the
                   4154:             probability to die within a month. Thanks to Chris
                   4155:             Jackson for correcting this bug.  Former versions increased
                   4156:             mortality artificially. The bad side is that we add another loop
                   4157:             which slows down the processing. The difference can be up to 10%
                   4158:             lower mortality.
                   4159:          */
                   4160:          /* If, at the beginning of the maximization mostly, the
                   4161:             cumulative probability or probability to be dead is
                   4162:             constant (ie = 1) over time d, the difference is equal to
                   4163:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4164:             s1 at precedent wave, to be dead a month before current
                   4165:             wave is equal to probability, being at state s1 at
                   4166:             precedent wave, to be dead at mont of the current
                   4167:             wave. Then the observed probability (that this person died)
                   4168:             is null according to current estimated parameter. In fact,
                   4169:             it should be very low but not zero otherwise the log go to
                   4170:             infinity.
                   4171:          */
1.183     brouard  4172: /* #ifdef INFINITYORIGINAL */
                   4173: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4174: /* #else */
                   4175: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4176: /*         lli=log(mytinydouble); */
                   4177: /*       else */
                   4178: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4179: /* #endif */
1.226     brouard  4180:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4181:          
1.226     brouard  4182:        } else if  ( s2==-1 ) { /* alive */
                   4183:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4184:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4185:          /*survp += out[s1][j]; */
                   4186:          lli= log(survp);
                   4187:        }
1.336     brouard  4188:        /* else if  (s2==-4) {  */
                   4189:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4190:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4191:        /*   lli= log(survp);  */
                   4192:        /* }  */
                   4193:        /* else if  (s2==-5) {  */
                   4194:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4195:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4196:        /*   lli= log(survp);  */
                   4197:        /* }  */
1.226     brouard  4198:        else{
                   4199:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4200:          /*  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 */
                   4201:        } 
                   4202:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4203:        /*if(lli ==000.0)*/
1.340     brouard  4204:        /* 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  4205:        ipmx +=1;
                   4206:        sw += weight[i];
                   4207:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4208:        /* if (lli < log(mytinydouble)){ */
                   4209:        /*   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); */
                   4210:        /*   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]); */
                   4211:        /* } */
                   4212:       } /* end of wave */
                   4213:     } /* end of individual */
                   4214:   }  else if(mle==2){
                   4215:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4216:       ioffset=2+nagesqr ;
                   4217:       for (k=1; k<=ncovf;k++)
                   4218:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4219:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4220:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4221:          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  4222:        }
1.226     brouard  4223:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4224:          for (j=1;j<=nlstate+ndeath;j++){
                   4225:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4226:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4227:          }
                   4228:        for(d=0; d<=dh[mi][i]; d++){
                   4229:          newm=savm;
                   4230:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4231:          cov[2]=agexact;
                   4232:          if(nagesqr==1)
                   4233:            cov[3]= agexact*agexact;
                   4234:          for (kk=1; kk<=cptcovage;kk++) {
                   4235:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4236:          }
                   4237:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4238:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4239:          savm=oldm;
                   4240:          oldm=newm;
                   4241:        } /* end mult */
                   4242:       
                   4243:        s1=s[mw[mi][i]][i];
                   4244:        s2=s[mw[mi+1][i]][i];
                   4245:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4246:        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 */
                   4247:        ipmx +=1;
                   4248:        sw += weight[i];
                   4249:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4250:       } /* end of wave */
                   4251:     } /* end of individual */
                   4252:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4253:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4254:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4255:       for(mi=1; mi<= wav[i]-1; mi++){
                   4256:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4257:          for (j=1;j<=nlstate+ndeath;j++){
                   4258:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4259:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4260:          }
                   4261:        for(d=0; d<dh[mi][i]; d++){
                   4262:          newm=savm;
                   4263:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4264:          cov[2]=agexact;
                   4265:          if(nagesqr==1)
                   4266:            cov[3]= agexact*agexact;
                   4267:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4268:            if(!FixedV[Tvar[Tage[kk]]])
                   4269:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4270:            else
1.341     brouard  4271:              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  4272:          }
                   4273:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4274:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4275:          savm=oldm;
                   4276:          oldm=newm;
                   4277:        } /* end mult */
                   4278:       
                   4279:        s1=s[mw[mi][i]][i];
                   4280:        s2=s[mw[mi+1][i]][i];
                   4281:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4282:        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 */
                   4283:        ipmx +=1;
                   4284:        sw += weight[i];
                   4285:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4286:       } /* end of wave */
                   4287:     } /* end of individual */
                   4288:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4289:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4290:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4291:       for(mi=1; mi<= wav[i]-1; mi++){
                   4292:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4293:          for (j=1;j<=nlstate+ndeath;j++){
                   4294:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4295:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4296:          }
                   4297:        for(d=0; d<dh[mi][i]; d++){
                   4298:          newm=savm;
                   4299:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4300:          cov[2]=agexact;
                   4301:          if(nagesqr==1)
                   4302:            cov[3]= agexact*agexact;
                   4303:          for (kk=1; kk<=cptcovage;kk++) {
                   4304:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4305:          }
1.126     brouard  4306:        
1.226     brouard  4307:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4308:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4309:          savm=oldm;
                   4310:          oldm=newm;
                   4311:        } /* end mult */
                   4312:       
                   4313:        s1=s[mw[mi][i]][i];
                   4314:        s2=s[mw[mi+1][i]][i];
                   4315:        if( s2 > nlstate){ 
                   4316:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4317:        } else if  ( s2==-1 ) { /* alive */
                   4318:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4319:            survp += out[s1][j];
                   4320:          lli= log(survp);
                   4321:        }else{
                   4322:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4323:        }
                   4324:        ipmx +=1;
                   4325:        sw += weight[i];
                   4326:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4327:        /* 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  4328:       } /* end of wave */
                   4329:     } /* end of individual */
                   4330:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4331:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4332:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4333:       for(mi=1; mi<= wav[i]-1; mi++){
                   4334:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4335:          for (j=1;j<=nlstate+ndeath;j++){
                   4336:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4337:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4338:          }
                   4339:        for(d=0; d<dh[mi][i]; d++){
                   4340:          newm=savm;
                   4341:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4342:          cov[2]=agexact;
                   4343:          if(nagesqr==1)
                   4344:            cov[3]= agexact*agexact;
                   4345:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4346:            if(!FixedV[Tvar[Tage[kk]]])
                   4347:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4348:            else
1.341     brouard  4349:              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  4350:          }
1.126     brouard  4351:        
1.226     brouard  4352:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4353:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4354:          savm=oldm;
                   4355:          oldm=newm;
                   4356:        } /* end mult */
                   4357:       
                   4358:        s1=s[mw[mi][i]][i];
                   4359:        s2=s[mw[mi+1][i]][i];
                   4360:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4361:        ipmx +=1;
                   4362:        sw += weight[i];
                   4363:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4364:        /*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]);*/
                   4365:       } /* end of wave */
                   4366:     } /* end of individual */
                   4367:   } /* End of if */
                   4368:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4369:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4370:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4371:   return -l;
1.126     brouard  4372: }
                   4373: 
                   4374: /*************** log-likelihood *************/
                   4375: double funcone( double *x)
                   4376: {
1.228     brouard  4377:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4378:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4379:   int ioffset=0;
1.339     brouard  4380:   int ipos=0,iposold=0,ncovv=0;
                   4381: 
1.340     brouard  4382:   double cotvarv, cotvarvold;
1.131     brouard  4383:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4384:   double **out;
                   4385:   double lli; /* Individual log likelihood */
                   4386:   double llt;
                   4387:   int s1, s2;
1.228     brouard  4388:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4389: 
1.126     brouard  4390:   double bbh, survp;
1.187     brouard  4391:   double agexact;
1.214     brouard  4392:   double agebegin, ageend;
1.126     brouard  4393:   /*extern weight */
                   4394:   /* We are differentiating ll according to initial status */
                   4395:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4396:   /*for(i=1;i<imx;i++) 
                   4397:     printf(" %d\n",s[4][i]);
                   4398:   */
                   4399:   cov[1]=1.;
                   4400: 
                   4401:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4402:   ioffset=0;
                   4403:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4404:     /* Computes the values of the ncovmodel covariates of the model
                   4405:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4406:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4407:        to be observed in j being in i according to the model.
                   4408:     */
1.243     brouard  4409:     /* ioffset=2+nagesqr+cptcovage; */
                   4410:     ioffset=2+nagesqr;
1.232     brouard  4411:     /* Fixed */
1.224     brouard  4412:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4413:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4414:     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  4415:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4416:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4417:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4418:       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  4419: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4420: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4421: /*    cov[2+6]=covar[2][i]; V2  */
                   4422: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4423: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4424: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4425: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4426: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4427: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4428:     }
1.336     brouard  4429:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4430:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4431:         has been calculated etc */
                   4432:       /* For an individual i, wav[i] gives the number of effective waves */
                   4433:       /* We compute the contribution to Likelihood of each effective transition
                   4434:         mw[mi][i] is real wave of the mi th effectve wave */
                   4435:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4436:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4437:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4438:       */
                   4439:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4440:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4441:     /*   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?)*\/ */
                   4442:     /* } */
1.231     brouard  4443:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4444:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4445:     /* } */
1.225     brouard  4446:     
1.233     brouard  4447: 
                   4448:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4449:       /* 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 */
                   4450:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4451:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4452:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4453:       /* } */
                   4454:       
                   4455:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4456:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4457:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4458:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4459:       /* We need the position of the time varying or product in the model */
                   4460:       /* 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 */            
                   4461:       /* TvarVV gives the variable name */
1.340     brouard  4462:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4463:       *      k=         1   2     3     4         5        6        7       8        9
                   4464:       *  varying            1     2                                 3       4        5
                   4465:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4466:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4467:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4468:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4469:       */
1.345     brouard  4470:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4471:        * 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  4472:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4473:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4474:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4475:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4476:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4477:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4478:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4479:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4480:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4481:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4482:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4483:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4484:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4485:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4486:        *                  12       13      14      15       16
                   4487:        *                    17        18         19        20         21
                   4488:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4489:        *                   2       3        4       6        7
                   4490:        *                     9         11          12        13         14            
                   4491:        * cptcovage=5+5 total of covariates with age 
                   4492:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4493:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4494:        *3 Tage[cptcovage] age*V3*V2=6  
                   4495:        *3                age*V2=12         13      14      15       16
                   4496:        *3                age*V6*V3=18      19    20   21
                   4497:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4498:        *     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
                   4499:        * 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
                   4500:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4501:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4502:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4503:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4504:        * 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
                   4505:        * Tvar=                {2, 3, 4, 6, 7,
                   4506:        *                       9, 10, 11, 12, 13, 14,
                   4507:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4508:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4509:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4510:        *                  2, 2, 2, 2, 2, 2,
                   4511:        * 3                3, 2, 2, 2, 2, 2,
                   4512:        *                  1, 1, 1, 1, 1, 
                   4513:        *                  3, 3, 3, 3, 3}
                   4514:        * 3                 2, 3, 3, 3, 3}
                   4515:        * 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
                   4516:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4517:        * 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}
                   4518:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4519:        * cptcovprod=11 (6+5)
                   4520:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4521:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4522:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4523:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4524:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4525:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4526:        * cptcovdageprod=5  for gnuplot printing
                   4527:        * cptcovprodvage=6 
                   4528:        * ncova=15           1        2       3       4       5
                   4529:        *                      6 7        8 9      10 11        12 13     14 15
                   4530:        * TvarA              2        3       4       6       7
                   4531:        *                      6 2        6 7       7 3          6 4       7 4
                   4532:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4533:        * ncovf            1     2      3
1.349     brouard  4534:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4535:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4536:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4537:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4538:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4539:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4540:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4541:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4542:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4543:        * 3 cptcovprodvage=6
                   4544:        * 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
                   4545:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4546:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
                   4547:        * TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
                   4548:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4549:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4550:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4551:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4552:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4553:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4554:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4555:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4556:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4557:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4558:        *                   2, 3, 4, 6, 7,
                   4559:        *                     6, 8, 9, 10, 11}
1.345     brouard  4560:        * TvarFind[itv]                        0      0       0
                   4561:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4562:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4563:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4564:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4565:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4566:        */
                   4567: 
1.349     brouard  4568:       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 */
                   4569:        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  4570:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4571:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4572:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4573:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4574:        }else{ /* fixed covariate */
1.345     brouard  4575:          /* 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  4576:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.340     brouard  4577:        }
1.339     brouard  4578:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4579:          cotvarvold=cotvarv;
                   4580:        }else{ /* A second product */
                   4581:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4582:        }
                   4583:        iposold=ipos;
1.340     brouard  4584:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4585:        /* For products */
                   4586:       }
                   4587:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4588:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4589:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4590:       /*       /\*           1  2   3      4      5                         *\/ */
                   4591:       /*       /\*itv           1                                           *\/ */
                   4592:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4593:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4594:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4595:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4596:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4597:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4598:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4599:       /*       /\* 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]); *\/ */
                   4600:       /* } */
1.232     brouard  4601:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4602:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4603:       /*       /\* 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]); *\/ */
                   4604:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4605:       /* } */
1.126     brouard  4606:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4607:        for (j=1;j<=nlstate+ndeath;j++){
                   4608:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4609:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4610:        }
1.214     brouard  4611:       
                   4612:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4613:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4614:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4615:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4616:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4617:          and mw[mi+1][i]. dh depends on stepm.*/
                   4618:        newm=savm;
1.247     brouard  4619:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4620:        cov[2]=agexact;
                   4621:        if(nagesqr==1)
                   4622:          cov[3]= agexact*agexact;
1.349     brouard  4623:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4624:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4625:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4626:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4627:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4628:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4629:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4630:          }else{ /* fixed covariate */
                   4631:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4632:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4633:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4634:          }
                   4635:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4636:            cotvarvold=cotvarv;
                   4637:          }else{ /* A second product */
                   4638:            /* printf("DEBUG * \n"); */
                   4639:            cotvarv=cotvarv*cotvarvold;
                   4640:          }
                   4641:          iposold=ipos;
                   4642:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4643:          cov[ioffset+ipos]=cotvarv*agexact;
                   4644:          /* For products */
1.242     brouard  4645:        }
1.349     brouard  4646: 
1.242     brouard  4647:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4648:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4649:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4650:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4651:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4652:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4653:        savm=oldm;
                   4654:        oldm=newm;
1.126     brouard  4655:       } /* end mult */
1.336     brouard  4656:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4657:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4658:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4659:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4660:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4661:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4662:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4663:         * probability in order to take into account the bias as a fraction of the way
                   4664:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4665:                                 * -stepm/2 to stepm/2 .
                   4666:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4667:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4668:                                 */
1.126     brouard  4669:       s1=s[mw[mi][i]][i];
                   4670:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4671:       /* if(s2==-1){ */
1.268     brouard  4672:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4673:       /*       /\* exit(1); *\/ */
                   4674:       /* } */
1.126     brouard  4675:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4676:       /* bias is positive if real duration
                   4677:        * is higher than the multiple of stepm and negative otherwise.
                   4678:        */
                   4679:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4680:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4681:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4682:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4683:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4684:        lli= log(survp);
1.126     brouard  4685:       }else if (mle==1){
1.242     brouard  4686:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4687:       } else if(mle==2){
1.242     brouard  4688:        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  4689:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4690:        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  4691:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4692:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4693:       } else{  /* mle=0 back to 1 */
1.242     brouard  4694:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4695:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4696:       } /* End of if */
                   4697:       ipmx +=1;
                   4698:       sw += weight[i];
                   4699:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4700:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4701:       /* 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  4702:       if(globpr){
1.246     brouard  4703:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4704:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4705:                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  4706:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4707:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4708:        /* %11.6f %11.6f %11.6f ", \ */
                   4709:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4710:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4711:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4712:          llt +=ll[k]*gipmx/gsw;
                   4713:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4714:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4715:        }
1.343     brouard  4716:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4717:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4718:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4719:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4720:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4721:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4722:        }
                   4723:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4724:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4725:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4726:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4727:            /* printf(" %g",cov[ioffset+ipos]); */
                   4728:          }else{
                   4729:            fprintf(ficresilk,"*");
                   4730:            /* printf("*"); */
1.342     brouard  4731:          }
1.343     brouard  4732:          iposold=ipos;
                   4733:        }
1.349     brouard  4734:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4735:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4736:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4737:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4738:        /*   }else{ */
                   4739:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4740:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4741:        /*   } */
                   4742:        /* } */
                   4743:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4744:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4745:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4746:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4747:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4748:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4749:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4750:          }else{ /* fixed covariate */
                   4751:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4752:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4753:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4754:          }
                   4755:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4756:            cotvarvold=cotvarv;
                   4757:          }else{ /* A second product */
                   4758:            /* printf("DEBUG * \n"); */
                   4759:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4760:          }
1.349     brouard  4761:          cotvarv=cotvarv*agexact;
                   4762:          fprintf(ficresilk," %g*age",cotvarv);
                   4763:          iposold=ipos;
                   4764:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4765:          cov[ioffset+ipos]=cotvarv;
                   4766:          /* For products */
1.343     brouard  4767:        }
                   4768:        /* printf("\n"); */
1.342     brouard  4769:        /* } /\*  End debugILK *\/ */
                   4770:        fprintf(ficresilk,"\n");
                   4771:       } /* End if globpr */
1.335     brouard  4772:     } /* end of wave */
                   4773:   } /* end of individual */
                   4774:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4775: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4776:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4777:   if(globpr==0){ /* First time we count the contributions and weights */
                   4778:     gipmx=ipmx;
                   4779:     gsw=sw;
                   4780:   }
1.343     brouard  4781:   return -l;
1.126     brouard  4782: }
                   4783: 
                   4784: 
                   4785: /*************** function likelione ***********/
1.292     brouard  4786: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4787: {
                   4788:   /* This routine should help understanding what is done with 
                   4789:      the selection of individuals/waves and
                   4790:      to check the exact contribution to the likelihood.
                   4791:      Plotting could be done.
1.342     brouard  4792:   */
                   4793:   void pstamp(FILE *ficres);
1.343     brouard  4794:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4795: 
                   4796:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4797:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4798:     strcat(fileresilk,fileresu);
1.126     brouard  4799:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4800:       printf("Problem with resultfile: %s\n", fileresilk);
                   4801:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4802:     }
1.342     brouard  4803:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4804:     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");
                   4805:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4806:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4807:     for(k=1; k<=nlstate; k++) 
                   4808:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4809:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4810: 
                   4811:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4812:       for(kf=1;kf <= ncovf; kf++){
                   4813:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4814:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4815:       }
                   4816:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4817:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4818:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4819:          /* printf(" %d",ipos); */
                   4820:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4821:        }else{
                   4822:          /* printf("*"); */
                   4823:          fprintf(ficresilk,"*");
1.343     brouard  4824:        }
1.342     brouard  4825:        iposold=ipos;
                   4826:       }
                   4827:       for (kk=1; kk<=cptcovage;kk++) {
                   4828:        if(!FixedV[Tvar[Tage[kk]]]){
                   4829:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4830:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4831:        }else{
                   4832:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4833:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4834:        }
                   4835:       }
                   4836:     /* } /\* End if debugILK *\/ */
                   4837:     /* printf("\n"); */
                   4838:     fprintf(ficresilk,"\n");
                   4839:   } /* End glogpri */
1.126     brouard  4840: 
1.292     brouard  4841:   *fretone=(*func)(p);
1.126     brouard  4842:   if(*globpri !=0){
                   4843:     fclose(ficresilk);
1.205     brouard  4844:     if (mle ==0)
                   4845:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4846:     else if(mle >=1)
                   4847:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4848:     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  4849:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4850:       
1.207     brouard  4851:     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  4852: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4853:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4854: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4855:     
                   4856:     for (k=1; k<= nlstate ; k++) {
                   4857:       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 \
                   4858: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4859:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4860:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4861:         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): ",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]]);
                   4862:         fprintf(fichtm,"<a href=\"%s-p%dj-%d.png\">%s-p%dj-%d.png</a><br>",subdirf2(optionfilefiname,"ILK_"),k,kvar,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   4863:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4864:       }
                   4865:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4866:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4867:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4868:        /* 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]); */
                   4869:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4870:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4871:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4872:          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)  */
                   4873:            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> \
                   4874: <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);
                   4875:          } /* End only for dummies time varying (single?) */
                   4876:        }else{ /* Useless product */
                   4877:          /* printf("*"); */
                   4878:          /* fprintf(ficresilk,"*"); */ 
                   4879:        }
                   4880:        iposold=ipos;
                   4881:       } /* For each time varying covariate */
                   4882:     } /* End loop on states */
                   4883: 
                   4884: /*     if(debugILK){ */
                   4885: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4886: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4887: /*     for (k=1; k<= nlstate ; k++) { */
                   4888: /*       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> \ */
                   4889: /* <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]]); */
                   4890: /*     } */
                   4891: /*       } */
                   4892: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4893: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4894: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4895: /*     /\* 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]); *\/ */
                   4896: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4897: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4898: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4899: /*       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)  *\/ */
                   4900: /*         for (k=1; k<= nlstate ; k++) { */
                   4901: /*           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> \ */
                   4902: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4903: /*         } /\* End state *\/ */
                   4904: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4905: /*     }else{ /\* Useless product *\/ */
                   4906: /*       /\* printf("*"); *\/ */
                   4907: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4908: /*     } */
                   4909: /*     iposold=ipos; */
                   4910: /*       } /\* For each time varying covariate *\/ */
                   4911: /*     }/\* End debugILK *\/ */
1.207     brouard  4912:     fflush(fichtm);
1.343     brouard  4913:   }/* End globpri */
1.126     brouard  4914:   return;
                   4915: }
                   4916: 
                   4917: 
                   4918: /*********** Maximum Likelihood Estimation ***************/
                   4919: 
                   4920: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4921: {
1.319     brouard  4922:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4923:   double **xi;
                   4924:   double fret;
                   4925:   double fretone; /* Only one call to likelihood */
                   4926:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4927: 
                   4928: #ifdef NLOPT
                   4929:   int creturn;
                   4930:   nlopt_opt opt;
                   4931:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4932:   double *lb;
                   4933:   double minf; /* the minimum objective value, upon return */
                   4934:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4935:   myfunc_data dinst, *d = &dinst;
                   4936: #endif
                   4937: 
                   4938: 
1.126     brouard  4939:   xi=matrix(1,npar,1,npar);
                   4940:   for (i=1;i<=npar;i++)
                   4941:     for (j=1;j<=npar;j++)
                   4942:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4943:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4944:   strcpy(filerespow,"POW_"); 
1.126     brouard  4945:   strcat(filerespow,fileres);
                   4946:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4947:     printf("Problem with resultfile: %s\n", filerespow);
                   4948:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4949:   }
                   4950:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4951:   for (i=1;i<=nlstate;i++)
                   4952:     for(j=1;j<=nlstate+ndeath;j++)
                   4953:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4954:   fprintf(ficrespow,"\n");
1.162     brouard  4955: #ifdef POWELL
1.319     brouard  4956: #ifdef LINMINORIGINAL
                   4957: #else /* LINMINORIGINAL */
                   4958:   
                   4959:   flatdir=ivector(1,npar); 
                   4960:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4961: #endif /*LINMINORIGINAL */
                   4962: 
                   4963: #ifdef FLATSUP
                   4964:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4965:   /* reorganizing p by suppressing flat directions */
                   4966:   for(i=1, jk=1; i <=nlstate; i++){
                   4967:     for(k=1; k <=(nlstate+ndeath); k++){
                   4968:       if (k != i) {
                   4969:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4970:         if(flatdir[jk]==1){
                   4971:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4972:         }
                   4973:         for(j=1; j <=ncovmodel; j++){
                   4974:           printf("%12.7f ",p[jk]);
                   4975:           jk++; 
                   4976:         }
                   4977:         printf("\n");
                   4978:       }
                   4979:     }
                   4980:   }
                   4981: /* skipping */
                   4982:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4983:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4984:     for(k=1; k <=(nlstate+ndeath); k++){
                   4985:       if (k != i) {
                   4986:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4987:         if(flatdir[jk]==1){
                   4988:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4989:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4990:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4991:             /*q[jjk]=p[jk];*/
                   4992:           }
                   4993:         }else{
                   4994:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4995:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4996:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4997:             /*q[jjk]=p[jk];*/
                   4998:           }
                   4999:         }
                   5000:         printf("\n");
                   5001:       }
                   5002:       fflush(stdout);
                   5003:     }
                   5004:   }
                   5005:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5006: #else  /* FLATSUP */
1.126     brouard  5007:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5008: #endif  /* FLATSUP */
                   5009: 
                   5010: #ifdef LINMINORIGINAL
                   5011: #else
                   5012:       free_ivector(flatdir,1,npar); 
                   5013: #endif  /* LINMINORIGINAL*/
                   5014: #endif /* POWELL */
1.126     brouard  5015: 
1.162     brouard  5016: #ifdef NLOPT
                   5017: #ifdef NEWUOA
                   5018:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5019: #else
                   5020:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5021: #endif
                   5022:   lb=vector(0,npar-1);
                   5023:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5024:   nlopt_set_lower_bounds(opt, lb);
                   5025:   nlopt_set_initial_step1(opt, 0.1);
                   5026:   
                   5027:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5028:   d->function = func;
                   5029:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5030:   nlopt_set_min_objective(opt, myfunc, d);
                   5031:   nlopt_set_xtol_rel(opt, ftol);
                   5032:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5033:     printf("nlopt failed! %d\n",creturn); 
                   5034:   }
                   5035:   else {
                   5036:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5037:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5038:     iter=1; /* not equal */
                   5039:   }
                   5040:   nlopt_destroy(opt);
                   5041: #endif
1.319     brouard  5042: #ifdef FLATSUP
                   5043:   /* npared = npar -flatd/ncovmodel; */
                   5044:   /* xired= matrix(1,npared,1,npared); */
                   5045:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5046:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5047:   /* free_matrix(xire,1,npared,1,npared); */
                   5048: #else  /* FLATSUP */
                   5049: #endif /* FLATSUP */
1.126     brouard  5050:   free_matrix(xi,1,npar,1,npar);
                   5051:   fclose(ficrespow);
1.203     brouard  5052:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5053:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5054:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5055: 
                   5056: }
                   5057: 
                   5058: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5059: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5060: {
                   5061:   double  **a,**y,*x,pd;
1.203     brouard  5062:   /* double **hess; */
1.164     brouard  5063:   int i, j;
1.126     brouard  5064:   int *indx;
                   5065: 
                   5066:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5067:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5068:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5069:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5070:   double gompertz(double p[]);
1.203     brouard  5071:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5072: 
                   5073:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5074:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5075:   for (i=1;i<=npar;i++){
1.203     brouard  5076:     printf("%d-",i);fflush(stdout);
                   5077:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5078:    
                   5079:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5080:     
                   5081:     /*  printf(" %f ",p[i]);
                   5082:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5083:   }
                   5084:   
                   5085:   for (i=1;i<=npar;i++) {
                   5086:     for (j=1;j<=npar;j++)  {
                   5087:       if (j>i) { 
1.203     brouard  5088:        printf(".%d-%d",i,j);fflush(stdout);
                   5089:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5090:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5091:        
                   5092:        hess[j][i]=hess[i][j];    
                   5093:        /*printf(" %lf ",hess[i][j]);*/
                   5094:       }
                   5095:     }
                   5096:   }
                   5097:   printf("\n");
                   5098:   fprintf(ficlog,"\n");
                   5099: 
                   5100:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5101:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5102:   
                   5103:   a=matrix(1,npar,1,npar);
                   5104:   y=matrix(1,npar,1,npar);
                   5105:   x=vector(1,npar);
                   5106:   indx=ivector(1,npar);
                   5107:   for (i=1;i<=npar;i++)
                   5108:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5109:   ludcmp(a,npar,indx,&pd);
                   5110: 
                   5111:   for (j=1;j<=npar;j++) {
                   5112:     for (i=1;i<=npar;i++) x[i]=0;
                   5113:     x[j]=1;
                   5114:     lubksb(a,npar,indx,x);
                   5115:     for (i=1;i<=npar;i++){ 
                   5116:       matcov[i][j]=x[i];
                   5117:     }
                   5118:   }
                   5119: 
                   5120:   printf("\n#Hessian matrix#\n");
                   5121:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5122:   for (i=1;i<=npar;i++) { 
                   5123:     for (j=1;j<=npar;j++) { 
1.203     brouard  5124:       printf("%.6e ",hess[i][j]);
                   5125:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5126:     }
                   5127:     printf("\n");
                   5128:     fprintf(ficlog,"\n");
                   5129:   }
                   5130: 
1.203     brouard  5131:   /* printf("\n#Covariance matrix#\n"); */
                   5132:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5133:   /* for (i=1;i<=npar;i++) {  */
                   5134:   /*   for (j=1;j<=npar;j++) {  */
                   5135:   /*     printf("%.6e ",matcov[i][j]); */
                   5136:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5137:   /*   } */
                   5138:   /*   printf("\n"); */
                   5139:   /*   fprintf(ficlog,"\n"); */
                   5140:   /* } */
                   5141: 
1.126     brouard  5142:   /* Recompute Inverse */
1.203     brouard  5143:   /* for (i=1;i<=npar;i++) */
                   5144:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5145:   /* ludcmp(a,npar,indx,&pd); */
                   5146: 
                   5147:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5148: 
                   5149:   /* for (j=1;j<=npar;j++) { */
                   5150:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5151:   /*   x[j]=1; */
                   5152:   /*   lubksb(a,npar,indx,x); */
                   5153:   /*   for (i=1;i<=npar;i++){  */
                   5154:   /*     y[i][j]=x[i]; */
                   5155:   /*     printf("%.3e ",y[i][j]); */
                   5156:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5157:   /*   } */
                   5158:   /*   printf("\n"); */
                   5159:   /*   fprintf(ficlog,"\n"); */
                   5160:   /* } */
                   5161: 
                   5162:   /* Verifying the inverse matrix */
                   5163: #ifdef DEBUGHESS
                   5164:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5165: 
1.203     brouard  5166:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5167:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5168: 
                   5169:   for (j=1;j<=npar;j++) {
                   5170:     for (i=1;i<=npar;i++){ 
1.203     brouard  5171:       printf("%.2f ",y[i][j]);
                   5172:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5173:     }
                   5174:     printf("\n");
                   5175:     fprintf(ficlog,"\n");
                   5176:   }
1.203     brouard  5177: #endif
1.126     brouard  5178: 
                   5179:   free_matrix(a,1,npar,1,npar);
                   5180:   free_matrix(y,1,npar,1,npar);
                   5181:   free_vector(x,1,npar);
                   5182:   free_ivector(indx,1,npar);
1.203     brouard  5183:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5184: 
                   5185: 
                   5186: }
                   5187: 
                   5188: /*************** hessian matrix ****************/
                   5189: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5190: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5191:   int i;
                   5192:   int l=1, lmax=20;
1.203     brouard  5193:   double k1,k2, res, fx;
1.132     brouard  5194:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5195:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5196:   int k=0,kmax=10;
                   5197:   double l1;
                   5198: 
                   5199:   fx=func(x);
                   5200:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5201:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5202:     l1=pow(10,l);
                   5203:     delts=delt;
                   5204:     for(k=1 ; k <kmax; k=k+1){
                   5205:       delt = delta*(l1*k);
                   5206:       p2[theta]=x[theta] +delt;
1.145     brouard  5207:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5208:       p2[theta]=x[theta]-delt;
                   5209:       k2=func(p2)-fx;
                   5210:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5211:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5212:       
1.203     brouard  5213: #ifdef DEBUGHESSII
1.126     brouard  5214:       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);
                   5215:       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);
                   5216: #endif
                   5217:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5218:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5219:        k=kmax;
                   5220:       }
                   5221:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5222:        k=kmax; l=lmax*10;
1.126     brouard  5223:       }
                   5224:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5225:        delts=delt;
                   5226:       }
1.203     brouard  5227:     } /* End loop k */
1.126     brouard  5228:   }
                   5229:   delti[theta]=delts;
                   5230:   return res; 
                   5231:   
                   5232: }
                   5233: 
1.203     brouard  5234: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5235: {
                   5236:   int i;
1.164     brouard  5237:   int l=1, lmax=20;
1.126     brouard  5238:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5239:   double p2[MAXPARM+1];
1.203     brouard  5240:   int k, kmax=1;
                   5241:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5242: 
                   5243:   int firstime=0;
1.203     brouard  5244:   
1.126     brouard  5245:   fx=func(x);
1.203     brouard  5246:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5247:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5248:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5249:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5250:     k1=func(p2)-fx;
                   5251:   
1.203     brouard  5252:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5253:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5254:     k2=func(p2)-fx;
                   5255:   
1.203     brouard  5256:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5257:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5258:     k3=func(p2)-fx;
                   5259:   
1.203     brouard  5260:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5261:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5262:     k4=func(p2)-fx;
1.203     brouard  5263:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5264:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5265:       firstime=1;
1.203     brouard  5266:       kmax=kmax+10;
1.208     brouard  5267:     }
                   5268:     if(kmax >=10 || firstime ==1){
1.246     brouard  5269:       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);
                   5270:       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  5271:       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);
                   5272:       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);
                   5273:     }
                   5274: #ifdef DEBUGHESSIJ
                   5275:     v1=hess[thetai][thetai];
                   5276:     v2=hess[thetaj][thetaj];
                   5277:     cv12=res;
                   5278:     /* Computing eigen value of Hessian matrix */
                   5279:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5280:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5281:     if ((lc2 <0) || (lc1 <0) ){
                   5282:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5283:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5284:       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);
                   5285:       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);
                   5286:     }
1.126     brouard  5287: #endif
                   5288:   }
                   5289:   return res;
                   5290: }
                   5291: 
1.203     brouard  5292:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5293: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5294: /* { */
                   5295: /*   int i; */
                   5296: /*   int l=1, lmax=20; */
                   5297: /*   double k1,k2,k3,k4,res,fx; */
                   5298: /*   double p2[MAXPARM+1]; */
                   5299: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5300: /*   int k=0,kmax=10; */
                   5301: /*   double l1; */
                   5302:   
                   5303: /*   fx=func(x); */
                   5304: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5305: /*     l1=pow(10,l); */
                   5306: /*     delts=delt; */
                   5307: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5308: /*       delt = delti*(l1*k); */
                   5309: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5310: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5311: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5312: /*       k1=func(p2)-fx; */
                   5313:       
                   5314: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5315: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5316: /*       k2=func(p2)-fx; */
                   5317:       
                   5318: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5319: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5320: /*       k3=func(p2)-fx; */
                   5321:       
                   5322: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5323: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5324: /*       k4=func(p2)-fx; */
                   5325: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5326: /* #ifdef DEBUGHESSIJ */
                   5327: /*       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); */
                   5328: /*       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); */
                   5329: /* #endif */
                   5330: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5331: /*     k=kmax; */
                   5332: /*       } */
                   5333: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5334: /*     k=kmax; l=lmax*10; */
                   5335: /*       } */
                   5336: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5337: /*     delts=delt; */
                   5338: /*       } */
                   5339: /*     } /\* End loop k *\/ */
                   5340: /*   } */
                   5341: /*   delti[theta]=delts; */
                   5342: /*   return res;  */
                   5343: /* } */
                   5344: 
                   5345: 
1.126     brouard  5346: /************** Inverse of matrix **************/
                   5347: void ludcmp(double **a, int n, int *indx, double *d) 
                   5348: { 
                   5349:   int i,imax,j,k; 
                   5350:   double big,dum,sum,temp; 
                   5351:   double *vv; 
                   5352:  
                   5353:   vv=vector(1,n); 
                   5354:   *d=1.0; 
                   5355:   for (i=1;i<=n;i++) { 
                   5356:     big=0.0; 
                   5357:     for (j=1;j<=n;j++) 
                   5358:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5359:     if (big == 0.0){
                   5360:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5361:       for (j=1;j<=n;j++) {
                   5362:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5363:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5364:       }
                   5365:       fflush(ficlog);
                   5366:       fclose(ficlog);
                   5367:       nrerror("Singular matrix in routine ludcmp"); 
                   5368:     }
1.126     brouard  5369:     vv[i]=1.0/big; 
                   5370:   } 
                   5371:   for (j=1;j<=n;j++) { 
                   5372:     for (i=1;i<j;i++) { 
                   5373:       sum=a[i][j]; 
                   5374:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5375:       a[i][j]=sum; 
                   5376:     } 
                   5377:     big=0.0; 
                   5378:     for (i=j;i<=n;i++) { 
                   5379:       sum=a[i][j]; 
                   5380:       for (k=1;k<j;k++) 
                   5381:        sum -= a[i][k]*a[k][j]; 
                   5382:       a[i][j]=sum; 
                   5383:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5384:        big=dum; 
                   5385:        imax=i; 
                   5386:       } 
                   5387:     } 
                   5388:     if (j != imax) { 
                   5389:       for (k=1;k<=n;k++) { 
                   5390:        dum=a[imax][k]; 
                   5391:        a[imax][k]=a[j][k]; 
                   5392:        a[j][k]=dum; 
                   5393:       } 
                   5394:       *d = -(*d); 
                   5395:       vv[imax]=vv[j]; 
                   5396:     } 
                   5397:     indx[j]=imax; 
                   5398:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5399:     if (j != n) { 
                   5400:       dum=1.0/(a[j][j]); 
                   5401:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5402:     } 
                   5403:   } 
                   5404:   free_vector(vv,1,n);  /* Doesn't work */
                   5405: ;
                   5406: } 
                   5407: 
                   5408: void lubksb(double **a, int n, int *indx, double b[]) 
                   5409: { 
                   5410:   int i,ii=0,ip,j; 
                   5411:   double sum; 
                   5412:  
                   5413:   for (i=1;i<=n;i++) { 
                   5414:     ip=indx[i]; 
                   5415:     sum=b[ip]; 
                   5416:     b[ip]=b[i]; 
                   5417:     if (ii) 
                   5418:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5419:     else if (sum) ii=i; 
                   5420:     b[i]=sum; 
                   5421:   } 
                   5422:   for (i=n;i>=1;i--) { 
                   5423:     sum=b[i]; 
                   5424:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5425:     b[i]=sum/a[i][i]; 
                   5426:   } 
                   5427: } 
                   5428: 
                   5429: void pstamp(FILE *fichier)
                   5430: {
1.196     brouard  5431:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5432: }
                   5433: 
1.297     brouard  5434: void date2dmy(double date,double *day, double *month, double *year){
                   5435:   double yp=0., yp1=0., yp2=0.;
                   5436:   
                   5437:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5438:                        fractional in yp1 */
                   5439:   *year=yp;
                   5440:   yp2=modf((yp1*12),&yp);
                   5441:   *month=yp;
                   5442:   yp1=modf((yp2*30.5),&yp);
                   5443:   *day=yp;
                   5444:   if(*day==0) *day=1;
                   5445:   if(*month==0) *month=1;
                   5446: }
                   5447: 
1.253     brouard  5448: 
                   5449: 
1.126     brouard  5450: /************ Frequencies ********************/
1.251     brouard  5451: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5452:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5453:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5454: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5455:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5456:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5457:   int iind=0, iage=0;
                   5458:   int mi; /* Effective wave */
                   5459:   int first;
                   5460:   double ***freq; /* Frequencies */
1.268     brouard  5461:   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 */
                   5462:   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  5463:   double *meanq, *stdq, *idq;
1.226     brouard  5464:   double **meanqt;
                   5465:   double *pp, **prop, *posprop, *pospropt;
                   5466:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5467:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5468:   double agebegin, ageend;
                   5469:     
                   5470:   pp=vector(1,nlstate);
1.251     brouard  5471:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5472:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5473:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5474:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5475:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5476:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5477:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5478:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5479:   strcpy(fileresp,"P_");
                   5480:   strcat(fileresp,fileresu);
                   5481:   /*strcat(fileresphtm,fileresu);*/
                   5482:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5483:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5484:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5485:     exit(0);
                   5486:   }
1.240     brouard  5487:   
1.226     brouard  5488:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5489:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5490:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5491:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5492:     fflush(ficlog);
                   5493:     exit(70); 
                   5494:   }
                   5495:   else{
                   5496:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5497: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5498: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5499:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5500:   }
1.319     brouard  5501:   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  5502:   
1.226     brouard  5503:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5504:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5505:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5506:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5507:     fflush(ficlog);
                   5508:     exit(70); 
1.240     brouard  5509:   } else{
1.226     brouard  5510:     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  5511: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5512: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5513:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5514:   }
1.319     brouard  5515:   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  5516:   
1.253     brouard  5517:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5518:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5519:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5520:   j1=0;
1.126     brouard  5521:   
1.227     brouard  5522:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5523:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5524:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5525:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5526:   
                   5527:   
1.226     brouard  5528:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5529:      reference=low_education V1=0,V2=0
                   5530:      med_educ                V1=1 V2=0, 
                   5531:      high_educ               V1=0 V2=1
1.330     brouard  5532:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5533:   */
1.249     brouard  5534:   dateintsum=0;
                   5535:   k2cpt=0;
                   5536: 
1.253     brouard  5537:   if(cptcoveff == 0 )
1.265     brouard  5538:     nl=1;  /* Constant and age model only */
1.253     brouard  5539:   else
                   5540:     nl=2;
1.265     brouard  5541: 
                   5542:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5543:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5544:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5545:    *     freq[s1][s2][iage] =0.
                   5546:    *     Loop on iind
                   5547:    *       ++freq[s1][s2][iage] weighted
                   5548:    *     end iind
                   5549:    *     if covariate and j!0
                   5550:    *       headers Variable on one line
                   5551:    *     endif cov j!=0
                   5552:    *     header of frequency table by age
                   5553:    *     Loop on age
                   5554:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5555:    *       pos+=freq[s1][s2][iage] weighted
                   5556:    *       Loop on s1 initial state
                   5557:    *         fprintf(ficresp
                   5558:    *       end s1
                   5559:    *     end age
                   5560:    *     if j!=0 computes starting values
                   5561:    *     end compute starting values
                   5562:    *   end j1
                   5563:    * end nl 
                   5564:    */
1.253     brouard  5565:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5566:     if(nj==1)
                   5567:       j=0;  /* First pass for the constant */
1.265     brouard  5568:     else{
1.335     brouard  5569:       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  5570:     }
1.251     brouard  5571:     first=1;
1.332     brouard  5572:     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  5573:       posproptt=0.;
1.330     brouard  5574:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5575:        scanf("%d", i);*/
                   5576:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5577:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5578:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5579:            freq[i][s2][m]=0;
1.251     brouard  5580:       
                   5581:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5582:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5583:          prop[i][m]=0;
                   5584:        posprop[i]=0;
                   5585:        pospropt[i]=0;
                   5586:       }
1.283     brouard  5587:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5588:         idq[z1]=0.;
                   5589:         meanq[z1]=0.;
                   5590:         stdq[z1]=0.;
1.283     brouard  5591:       }
                   5592:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5593:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5594:       /*         meanqt[m][z1]=0.; */
                   5595:       /*       } */
                   5596:       /* }       */
1.251     brouard  5597:       /* dateintsum=0; */
                   5598:       /* k2cpt=0; */
                   5599:       
1.265     brouard  5600:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5601:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5602:        bool=1;
                   5603:        if(j !=0){
                   5604:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5605:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5606:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5607:                /* if(Tvaraff[z1] ==-20){ */
                   5608:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5609:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5610:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5611:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5612:                /* 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); */
                   5613:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5614:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5615:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5616:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5617:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5618:                  /* 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", */
                   5619:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5620:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5621:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5622:                } /* Onlyf fixed */
                   5623:              } /* end z1 */
1.335     brouard  5624:            } /* cptcoveff > 0 */
1.251     brouard  5625:          } /* end any */
                   5626:        }/* end j==0 */
1.265     brouard  5627:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5628:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5629:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5630:            m=mw[mi][iind];
                   5631:            if(j!=0){
                   5632:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5633:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5634:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5635:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5636:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5637:                    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  5638:                                                                                      value is -1, we don't select. It differs from the 
                   5639:                                                                                      constant and age model which counts them. */
                   5640:                      bool=0; /* not selected */
                   5641:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5642:                    /* i1=Tvaraff[z1]; */
                   5643:                    /* i2=TnsdVar[i1]; */
                   5644:                    /* i3=nbcode[i1][i2]; */
                   5645:                    /* i4=covar[i1][iind]; */
                   5646:                    /* if(i4 != i3){ */
                   5647:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5648:                      bool=0;
                   5649:                    }
                   5650:                  }
                   5651:                }
                   5652:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5653:            } /* end j==0 */
                   5654:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5655:            if(bool==1){ /*Selected */
1.251     brouard  5656:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5657:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5658:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5659:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5660:              if(m >=firstpass && m <=lastpass){
                   5661:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5662:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5663:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5664:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5665:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5666:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5667:                if (m<lastpass) {
                   5668:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5669:                  /*   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]); */
                   5670:                  if(s[m][iind]==-1)
                   5671:                    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.));
                   5672:                  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  5673:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5674:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5675:                      idq[z1]=idq[z1]+weight[iind];
                   5676:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5677:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5678:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5679:                    }
1.284     brouard  5680:                  }
1.251     brouard  5681:                  /* if((int)agev[m][iind] == 55) */
                   5682:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5683:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5684:                  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  5685:                }
1.251     brouard  5686:              } /* end if between passes */  
                   5687:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5688:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5689:                k2cpt++;
                   5690:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5691:              }
1.251     brouard  5692:            }else{
                   5693:              bool=1;
                   5694:            }/* end bool 2 */
                   5695:          } /* end m */
1.284     brouard  5696:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5697:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5698:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5699:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5700:          /* } */
1.251     brouard  5701:        } /* end bool */
                   5702:       } /* end iind = 1 to imx */
1.319     brouard  5703:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5704:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5705:       
                   5706:       
                   5707:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5708:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5709:         pstamp(ficresp);
1.335     brouard  5710:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5711:         pstamp(ficresp);
1.251     brouard  5712:        printf( "\n#********** Variable "); 
                   5713:        fprintf(ficresp, "\n#********** Variable "); 
                   5714:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5715:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5716:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5717:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5718:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5719:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5720:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5721:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5722:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5723:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5724:          }else{
1.330     brouard  5725:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5726:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5727:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5728:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5729:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5730:          }
                   5731:        }
                   5732:        printf( "**********\n#");
                   5733:        fprintf(ficresp, "**********\n#");
                   5734:        fprintf(ficresphtm, "**********</h3>\n");
                   5735:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5736:        fprintf(ficlog, "**********\n");
                   5737:       }
1.284     brouard  5738:       /*
                   5739:        Printing means of quantitative variables if any
                   5740:       */
                   5741:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5742:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5743:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5744:        if(weightopt==1){
                   5745:          printf(" Weighted mean and standard deviation of");
                   5746:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5747:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5748:        }
1.311     brouard  5749:        /* mu = \frac{w x}{\sum w}
                   5750:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5751:        */
                   5752:        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]));
                   5753:        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]));
                   5754:        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  5755:       }
                   5756:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5757:       /*       for(m=1;m<=lastpass;m++){ */
                   5758:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5759:       /*   } */
                   5760:       /* } */
1.283     brouard  5761: 
1.251     brouard  5762:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5763:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5764:         fprintf(ficresp, " Age");
1.335     brouard  5765:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5766:          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]]);
                   5767:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5768:        }
1.251     brouard  5769:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5770:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5771:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5772:       }
1.335     brouard  5773:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5774:       fprintf(ficresphtm, "\n");
                   5775:       
                   5776:       /* Header of frequency table by age */
                   5777:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5778:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5779:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5780:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5781:          if(s2!=0 && m!=0)
                   5782:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5783:        }
1.226     brouard  5784:       }
1.251     brouard  5785:       fprintf(ficresphtmfr, "\n");
                   5786:     
                   5787:       /* For each age */
                   5788:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5789:        fprintf(ficresphtm,"<tr>");
                   5790:        if(iage==iagemax+1){
                   5791:          fprintf(ficlog,"1");
                   5792:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5793:        }else if(iage==iagemax+2){
                   5794:          fprintf(ficlog,"0");
                   5795:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5796:        }else if(iage==iagemax+3){
                   5797:          fprintf(ficlog,"Total");
                   5798:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5799:        }else{
1.240     brouard  5800:          if(first==1){
1.251     brouard  5801:            first=0;
                   5802:            printf("See log file for details...\n");
                   5803:          }
                   5804:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5805:          fprintf(ficlog,"Age %d", iage);
                   5806:        }
1.265     brouard  5807:        for(s1=1; s1 <=nlstate ; s1++){
                   5808:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5809:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5810:        }
1.265     brouard  5811:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5812:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5813:            pos += freq[s1][m][iage];
                   5814:          if(pp[s1]>=1.e-10){
1.251     brouard  5815:            if(first==1){
1.265     brouard  5816:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5817:            }
1.265     brouard  5818:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5819:          }else{
                   5820:            if(first==1)
1.265     brouard  5821:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5822:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5823:          }
                   5824:        }
                   5825:       
1.265     brouard  5826:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5827:          /* posprop[s1]=0; */
                   5828:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5829:            pp[s1] += freq[s1][m][iage];
                   5830:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5831:       
                   5832:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5833:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5834:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5835:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5836:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5837:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5838:        }
                   5839:        
                   5840:        /* Writing ficresp */
1.335     brouard  5841:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5842:           if( iage <= iagemax){
                   5843:            fprintf(ficresp," %d",iage);
                   5844:           }
                   5845:         }else if( nj==2){
                   5846:           if( iage <= iagemax){
                   5847:            fprintf(ficresp," %d",iage);
1.335     brouard  5848:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5849:           }
1.240     brouard  5850:        }
1.265     brouard  5851:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5852:          if(pos>=1.e-5){
1.251     brouard  5853:            if(first==1)
1.265     brouard  5854:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5855:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5856:          }else{
                   5857:            if(first==1)
1.265     brouard  5858:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5859:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5860:          }
                   5861:          if( iage <= iagemax){
                   5862:            if(pos>=1.e-5){
1.335     brouard  5863:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5864:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5865:               }else if( nj==2){
                   5866:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5867:               }
                   5868:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5869:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5870:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5871:            } else{
1.335     brouard  5872:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5873:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5874:            }
1.240     brouard  5875:          }
1.265     brouard  5876:          pospropt[s1] +=posprop[s1];
                   5877:        } /* end loop s1 */
1.251     brouard  5878:        /* pospropt=0.; */
1.265     brouard  5879:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5880:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5881:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5882:              if(first==1){
1.265     brouard  5883:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5884:              }
1.265     brouard  5885:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5886:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5887:            }
1.265     brouard  5888:            if(s1!=0 && m!=0)
                   5889:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5890:          }
1.265     brouard  5891:        } /* end loop s1 */
1.251     brouard  5892:        posproptt=0.; 
1.265     brouard  5893:        for(s1=1; s1 <=nlstate; s1++){
                   5894:          posproptt += pospropt[s1];
1.251     brouard  5895:        }
                   5896:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5897:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5898:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5899:          if(iage <= iagemax)
                   5900:            fprintf(ficresp,"\n");
1.240     brouard  5901:        }
1.251     brouard  5902:        if(first==1)
                   5903:          printf("Others in log...\n");
                   5904:        fprintf(ficlog,"\n");
                   5905:       } /* end loop age iage */
1.265     brouard  5906:       
1.251     brouard  5907:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5908:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5909:        if(posproptt < 1.e-5){
1.265     brouard  5910:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5911:        }else{
1.265     brouard  5912:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5913:        }
1.226     brouard  5914:       }
1.251     brouard  5915:       fprintf(ficresphtm,"</tr>\n");
                   5916:       fprintf(ficresphtm,"</table>\n");
                   5917:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5918:       if(posproptt < 1.e-5){
1.251     brouard  5919:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5920:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5921:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5922:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5923:        invalidvarcomb[j1]=1;
1.226     brouard  5924:       }else{
1.338     brouard  5925:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5926:        invalidvarcomb[j1]=0;
1.226     brouard  5927:       }
1.251     brouard  5928:       fprintf(ficresphtmfr,"</table>\n");
                   5929:       fprintf(ficlog,"\n");
                   5930:       if(j!=0){
                   5931:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5932:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5933:          for(k=1; k <=(nlstate+ndeath); k++){
                   5934:            if (k != i) {
1.265     brouard  5935:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5936:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5937:                  if(j1==1){ /* All dummy covariates to zero */
                   5938:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5939:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5940:                    printf("%d%d ",i,k);
                   5941:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5942:                    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]));
                   5943:                    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]));
                   5944:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5945:                  }
1.253     brouard  5946:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5947:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5948:                    x[iage]= (double)iage;
                   5949:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5950:                    /* 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  5951:                  }
1.268     brouard  5952:                  /* Some are not finite, but linreg will ignore these ages */
                   5953:                  no=0;
1.253     brouard  5954:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5955:                  pstart[s1]=b;
                   5956:                  pstart[s1-1]=a;
1.252     brouard  5957:                }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 */ 
                   5958:                  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]);
                   5959:                  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  5960:                  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  5961:                  printf("%d%d ",i,k);
                   5962:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5963:                  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  5964:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5965:                  ;
                   5966:                }
                   5967:                /* printf("%12.7f )", param[i][jj][k]); */
                   5968:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5969:                s1++; 
1.251     brouard  5970:              } /* end jj */
                   5971:            } /* end k!= i */
                   5972:          } /* end k */
1.265     brouard  5973:        } /* end i, s1 */
1.251     brouard  5974:       } /* end j !=0 */
                   5975:     } /* end selected combination of covariate j1 */
                   5976:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5977:       printf("#Freqsummary: Starting values for the constants:\n");
                   5978:       fprintf(ficlog,"\n");
1.265     brouard  5979:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5980:        for(k=1; k <=(nlstate+ndeath); k++){
                   5981:          if (k != i) {
                   5982:            printf("%d%d ",i,k);
                   5983:            fprintf(ficlog,"%d%d ",i,k);
                   5984:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5985:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5986:              if(jj==1){ /* Age has to be done */
1.265     brouard  5987:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5988:                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]));
                   5989:                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  5990:              }
                   5991:              /* printf("%12.7f )", param[i][jj][k]); */
                   5992:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5993:              s1++; 
1.250     brouard  5994:            }
1.251     brouard  5995:            printf("\n");
                   5996:            fprintf(ficlog,"\n");
1.250     brouard  5997:          }
                   5998:        }
1.284     brouard  5999:       } /* end of state i */
1.251     brouard  6000:       printf("#Freqsummary\n");
                   6001:       fprintf(ficlog,"\n");
1.265     brouard  6002:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6003:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6004:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6005:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6006:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6007:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6008:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6009:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6010:          /* } */
                   6011:        }
1.265     brouard  6012:       } /* end loop s1 */
1.251     brouard  6013:       
                   6014:       printf("\n");
                   6015:       fprintf(ficlog,"\n");
                   6016:     } /* end j=0 */
1.249     brouard  6017:   } /* end j */
1.252     brouard  6018: 
1.253     brouard  6019:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6020:     for(i=1, jk=1; i <=nlstate; i++){
                   6021:       for(j=1; j <=nlstate+ndeath; j++){
                   6022:        if(j!=i){
                   6023:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6024:          printf("%1d%1d",i,j);
                   6025:          fprintf(ficparo,"%1d%1d",i,j);
                   6026:          for(k=1; k<=ncovmodel;k++){
                   6027:            /*    printf(" %lf",param[i][j][k]); */
                   6028:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6029:            p[jk]=pstart[jk];
                   6030:            printf(" %f ",pstart[jk]);
                   6031:            fprintf(ficparo," %f ",pstart[jk]);
                   6032:            jk++;
                   6033:          }
                   6034:          printf("\n");
                   6035:          fprintf(ficparo,"\n");
                   6036:        }
                   6037:       }
                   6038:     }
                   6039:   } /* end mle=-2 */
1.226     brouard  6040:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6041:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6042:   
1.226     brouard  6043:   fclose(ficresp);
                   6044:   fclose(ficresphtm);
                   6045:   fclose(ficresphtmfr);
1.283     brouard  6046:   free_vector(idq,1,nqfveff);
1.226     brouard  6047:   free_vector(meanq,1,nqfveff);
1.284     brouard  6048:   free_vector(stdq,1,nqfveff);
1.226     brouard  6049:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6050:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6051:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6052:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6053:   free_vector(pospropt,1,nlstate);
                   6054:   free_vector(posprop,1,nlstate);
1.251     brouard  6055:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6056:   free_vector(pp,1,nlstate);
                   6057:   /* End of freqsummary */
                   6058: }
1.126     brouard  6059: 
1.268     brouard  6060: /* Simple linear regression */
                   6061: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6062: 
                   6063:   /* y=a+bx regression */
                   6064:   double   sumx = 0.0;                        /* sum of x                      */
                   6065:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6066:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6067:   double   sumy = 0.0;                        /* sum of y                      */
                   6068:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6069:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6070:   double yhat;
                   6071:   
                   6072:   double denom=0;
                   6073:   int i;
                   6074:   int ne=*no;
                   6075:   
                   6076:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6077:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6078:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6079:       continue;
                   6080:     }
                   6081:     ne=ne+1;
                   6082:     sumx  += x[i];       
                   6083:     sumx2 += x[i]*x[i];  
                   6084:     sumxy += x[i] * y[i];
                   6085:     sumy  += y[i];      
                   6086:     sumy2 += y[i]*y[i]; 
                   6087:     denom = (ne * sumx2 - sumx*sumx);
                   6088:     /* 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); */
                   6089:   } 
                   6090:   
                   6091:   denom = (ne * sumx2 - sumx*sumx);
                   6092:   if (denom == 0) {
                   6093:     // vertical, slope m is infinity
                   6094:     *b = INFINITY;
                   6095:     *a = 0;
                   6096:     if (r) *r = 0;
                   6097:     return 1;
                   6098:   }
                   6099:   
                   6100:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6101:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6102:   if (r!=NULL) {
                   6103:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6104:       sqrt((sumx2 - sumx*sumx/ne) *
                   6105:           (sumy2 - sumy*sumy/ne));
                   6106:   }
                   6107:   *no=ne;
                   6108:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6109:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6110:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6111:       continue;
                   6112:     }
                   6113:     ne=ne+1;
                   6114:     yhat = y[i] - *a -*b* x[i];
                   6115:     sume2  += yhat * yhat ;       
                   6116:     
                   6117:     denom = (ne * sumx2 - sumx*sumx);
                   6118:     /* 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); */
                   6119:   } 
                   6120:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6121:   *sa= *sb * sqrt(sumx2/ne);
                   6122:   
                   6123:   return 0; 
                   6124: }
                   6125: 
1.126     brouard  6126: /************ Prevalence ********************/
1.227     brouard  6127: 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)
                   6128: {  
                   6129:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6130:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6131:      We still use firstpass and lastpass as another selection.
                   6132:   */
1.126     brouard  6133:  
1.227     brouard  6134:   int i, m, jk, j1, bool, z1,j, iv;
                   6135:   int mi; /* Effective wave */
                   6136:   int iage;
                   6137:   double agebegin, ageend;
                   6138: 
                   6139:   double **prop;
                   6140:   double posprop; 
                   6141:   double  y2; /* in fractional years */
                   6142:   int iagemin, iagemax;
                   6143:   int first; /** to stop verbosity which is redirected to log file */
                   6144: 
                   6145:   iagemin= (int) agemin;
                   6146:   iagemax= (int) agemax;
                   6147:   /*pp=vector(1,nlstate);*/
1.251     brouard  6148:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6149:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6150:   j1=0;
1.222     brouard  6151:   
1.227     brouard  6152:   /*j=cptcoveff;*/
                   6153:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6154:   
1.288     brouard  6155:   first=0;
1.335     brouard  6156:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6157:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6158:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6159:        prop[i][iage]=0.0;
                   6160:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6161:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6162:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6163:     
                   6164:     for (i=1; i<=imx; i++) { /* Each individual */
                   6165:       bool=1;
                   6166:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6167:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6168:        m=mw[mi][i];
                   6169:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6170:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6171:        for (z1=1; z1<=cptcoveff; z1++){
                   6172:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6173:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6174:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6175:              bool=0;
                   6176:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6177:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6178:              bool=0;
                   6179:            }
                   6180:        }
                   6181:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6182:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6183:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6184:          if(m >=firstpass && m <=lastpass){
                   6185:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6186:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6187:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6188:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6189:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6190:                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); 
                   6191:                exit(1);
                   6192:              }
                   6193:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6194:                /*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]]);*/
                   6195:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6196:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6197:              } /* end valid statuses */ 
                   6198:            } /* end selection of dates */
                   6199:          } /* end selection of waves */
                   6200:        } /* end bool */
                   6201:       } /* end wave */
                   6202:     } /* end individual */
                   6203:     for(i=iagemin; i <= iagemax+3; i++){  
                   6204:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6205:        posprop += prop[jk][i]; 
                   6206:       } 
                   6207:       
                   6208:       for(jk=1; jk <=nlstate ; jk++){      
                   6209:        if( i <=  iagemax){ 
                   6210:          if(posprop>=1.e-5){ 
                   6211:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6212:          } else{
1.288     brouard  6213:            if(!first){
                   6214:              first=1;
1.266     brouard  6215:              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]);
                   6216:            }else{
1.288     brouard  6217:              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  6218:            }
                   6219:          }
                   6220:        } 
                   6221:       }/* end jk */ 
                   6222:     }/* end i */ 
1.222     brouard  6223:      /*} *//* end i1 */
1.227     brouard  6224:   } /* end j1 */
1.222     brouard  6225:   
1.227     brouard  6226:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6227:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6228:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6229: }  /* End of prevalence */
1.126     brouard  6230: 
                   6231: /************* Waves Concatenation ***************/
                   6232: 
                   6233: 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)
                   6234: {
1.298     brouard  6235:   /* 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  6236:      Death is a valid wave (if date is known).
                   6237:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6238:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6239:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6240:   */
1.126     brouard  6241: 
1.224     brouard  6242:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6243:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6244:      double sum=0., jmean=0.;*/
1.224     brouard  6245:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6246:   int j, k=0,jk, ju, jl;
                   6247:   double sum=0.;
                   6248:   first=0;
1.214     brouard  6249:   firstwo=0;
1.217     brouard  6250:   firsthree=0;
1.218     brouard  6251:   firstfour=0;
1.164     brouard  6252:   jmin=100000;
1.126     brouard  6253:   jmax=-1;
                   6254:   jmean=0.;
1.224     brouard  6255: 
                   6256: /* Treating live states */
1.214     brouard  6257:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6258:     mi=0;  /* First valid wave */
1.227     brouard  6259:     mli=0; /* Last valid wave */
1.309     brouard  6260:     m=firstpass;  /* Loop on waves */
                   6261:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6262:       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 */
                   6263:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6264:       }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  6265:        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  6266:        mli=m;
1.224     brouard  6267:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6268:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6269:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6270:       }
1.309     brouard  6271:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6272: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6273:        break;
1.224     brouard  6274: #else
1.317     brouard  6275:        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  6276:          if(firsthree == 0){
1.302     brouard  6277:            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  6278:            firsthree=1;
1.317     brouard  6279:          }else if(firsthree >=1 && firsthree < 10){
                   6280:            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);
                   6281:            firsthree++;
                   6282:          }else if(firsthree == 10){
                   6283:            printf("Information, too many Information flags: no more reported to log either\n");
                   6284:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6285:            firsthree++;
                   6286:          }else{
                   6287:            firsthree++;
1.227     brouard  6288:          }
1.309     brouard  6289:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6290:          mli=m;
                   6291:        }
                   6292:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6293:          nbwarn++;
1.309     brouard  6294:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6295:            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);
                   6296:            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);
                   6297:          }
                   6298:          break;
                   6299:        }
                   6300:        break;
1.224     brouard  6301: #endif
1.227     brouard  6302:       }/* End m >= lastpass */
1.126     brouard  6303:     }/* end while */
1.224     brouard  6304: 
1.227     brouard  6305:     /* 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  6306:     /* After last pass */
1.224     brouard  6307: /* Treating death states */
1.214     brouard  6308:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6309:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6310:       /* } */
1.126     brouard  6311:       mi++;    /* Death is another wave */
                   6312:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6313:       /* Only death is a correct wave */
1.126     brouard  6314:       mw[mi][i]=m;
1.257     brouard  6315:     } /* else not in a death state */
1.224     brouard  6316: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6317:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6318:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6319:        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  6320:          nbwarn++;
                   6321:          if(firstfiv==0){
1.309     brouard  6322:            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  6323:            firstfiv=1;
                   6324:          }else{
1.309     brouard  6325:            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  6326:          }
1.309     brouard  6327:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6328:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6329:          nberr++;
                   6330:          if(firstwo==0){
1.309     brouard  6331:            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  6332:            firstwo=1;
                   6333:          }
1.309     brouard  6334:          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  6335:        }
1.257     brouard  6336:       }else{ /* if date of interview is unknown */
1.227     brouard  6337:        /* death is known but not confirmed by death status at any wave */
                   6338:        if(firstfour==0){
1.309     brouard  6339:          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  6340:          firstfour=1;
                   6341:        }
1.309     brouard  6342:        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  6343:       }
1.224     brouard  6344:     } /* end if date of death is known */
                   6345: #endif
1.309     brouard  6346:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6347:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6348:     if(mi==0){
                   6349:       nbwarn++;
                   6350:       if(first==0){
1.227     brouard  6351:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6352:        first=1;
1.126     brouard  6353:       }
                   6354:       if(first==1){
1.227     brouard  6355:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6356:       }
                   6357:     } /* end mi==0 */
                   6358:   } /* End individuals */
1.214     brouard  6359:   /* wav and mw are no more changed */
1.223     brouard  6360:        
1.317     brouard  6361:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6362:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6363: 
                   6364: 
1.126     brouard  6365:   for(i=1; i<=imx; i++){
                   6366:     for(mi=1; mi<wav[i];mi++){
                   6367:       if (stepm <=0)
1.227     brouard  6368:        dh[mi][i]=1;
1.126     brouard  6369:       else{
1.260     brouard  6370:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6371:          if (agedc[i] < 2*AGESUP) {
                   6372:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6373:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6374:            else if(j<0){
                   6375:              nberr++;
                   6376:              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]);
                   6377:              j=1; /* Temporary Dangerous patch */
                   6378:              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);
                   6379:              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]);
                   6380:              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);
                   6381:            }
                   6382:            k=k+1;
                   6383:            if (j >= jmax){
                   6384:              jmax=j;
                   6385:              ijmax=i;
                   6386:            }
                   6387:            if (j <= jmin){
                   6388:              jmin=j;
                   6389:              ijmin=i;
                   6390:            }
                   6391:            sum=sum+j;
                   6392:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6393:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6394:          }
                   6395:        }
                   6396:        else{
                   6397:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6398: /*       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  6399:                                        
1.227     brouard  6400:          k=k+1;
                   6401:          if (j >= jmax) {
                   6402:            jmax=j;
                   6403:            ijmax=i;
                   6404:          }
                   6405:          else if (j <= jmin){
                   6406:            jmin=j;
                   6407:            ijmin=i;
                   6408:          }
                   6409:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6410:          /*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]);*/
                   6411:          if(j<0){
                   6412:            nberr++;
                   6413:            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]);
                   6414:            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]);
                   6415:          }
                   6416:          sum=sum+j;
                   6417:        }
                   6418:        jk= j/stepm;
                   6419:        jl= j -jk*stepm;
                   6420:        ju= j -(jk+1)*stepm;
                   6421:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6422:          if(jl==0){
                   6423:            dh[mi][i]=jk;
                   6424:            bh[mi][i]=0;
                   6425:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6426:                  * to avoid the price of an extra matrix product in likelihood */
                   6427:            dh[mi][i]=jk+1;
                   6428:            bh[mi][i]=ju;
                   6429:          }
                   6430:        }else{
                   6431:          if(jl <= -ju){
                   6432:            dh[mi][i]=jk;
                   6433:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6434:                                 * is higher than the multiple of stepm and negative otherwise.
                   6435:                                 */
                   6436:          }
                   6437:          else{
                   6438:            dh[mi][i]=jk+1;
                   6439:            bh[mi][i]=ju;
                   6440:          }
                   6441:          if(dh[mi][i]==0){
                   6442:            dh[mi][i]=1; /* At least one step */
                   6443:            bh[mi][i]=ju; /* At least one step */
                   6444:            /*  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);*/
                   6445:          }
                   6446:        } /* end if mle */
1.126     brouard  6447:       }
                   6448:     } /* end wave */
                   6449:   }
                   6450:   jmean=sum/k;
                   6451:   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  6452:   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  6453: }
1.126     brouard  6454: 
                   6455: /*********** Tricode ****************************/
1.220     brouard  6456:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6457:  {
                   6458:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6459:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6460:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6461:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6462:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6463:     */
1.130     brouard  6464: 
1.242     brouard  6465:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6466:    int modmaxcovj=0; /* Modality max of covariates j */
                   6467:    int cptcode=0; /* Modality max of covariates j */
                   6468:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6469: 
                   6470: 
1.242     brouard  6471:    /* cptcoveff=0;  */
                   6472:    /* *cptcov=0; */
1.126     brouard  6473:  
1.242     brouard  6474:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6475:    for (k=1; k <= maxncov; k++)
                   6476:      for(j=1; j<=2; j++)
                   6477:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6478: 
1.242     brouard  6479:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6480:    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  6481:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6482:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6483:      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  6484:        switch(Fixed[k]) {
                   6485:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6486:         modmaxcovj=0;
                   6487:         modmincovj=0;
1.242     brouard  6488:         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  6489:           /* 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  6490:           ij=(int)(covar[Tvar[k]][i]);
                   6491:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6492:            * If product of Vn*Vm, still boolean *:
                   6493:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6494:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6495:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6496:              modality of the nth covariate of individual i. */
                   6497:           if (ij > modmaxcovj)
                   6498:             modmaxcovj=ij; 
                   6499:           else if (ij < modmincovj) 
                   6500:             modmincovj=ij; 
1.287     brouard  6501:           if (ij <0 || ij >1 ){
1.311     brouard  6502:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6503:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6504:             fflush(ficlog);
                   6505:             exit(1);
1.287     brouard  6506:           }
                   6507:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6508:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6509:             exit(1);
                   6510:           }else
                   6511:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6512:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6513:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6514:           /* getting the maximum value of the modality of the covariate
                   6515:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6516:              female ies 1, then modmaxcovj=1.
                   6517:           */
                   6518:         } /* end for loop on individuals i */
                   6519:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6520:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6521:         cptcode=modmaxcovj;
                   6522:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6523:         /*for (i=0; i<=cptcode; i++) {*/
                   6524:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6525:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6526:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6527:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6528:             if( j != -1){
                   6529:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6530:                                  covariate for which somebody answered excluding 
                   6531:                                  undefined. Usually 2: 0 and 1. */
                   6532:             }
                   6533:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6534:                                     covariate for which somebody answered including 
                   6535:                                     undefined. Usually 3: -1, 0 and 1. */
                   6536:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6537:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6538:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6539:                        
1.242     brouard  6540:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6541:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6542:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6543:         /* modmincovj=3; modmaxcovj = 7; */
                   6544:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6545:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6546:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6547:         /* nbcode[Tvar[j]][ij]=k; */
                   6548:         /* nbcode[Tvar[j]][1]=0; */
                   6549:         /* nbcode[Tvar[j]][2]=1; */
                   6550:         /* nbcode[Tvar[j]][3]=2; */
                   6551:         /* To be continued (not working yet). */
                   6552:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6553: 
                   6554:         /* 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*/
                   6555:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6556:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6557:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6558:         /*, could be restored in the future */
                   6559:         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  6560:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6561:             break;
                   6562:           }
                   6563:           ij++;
1.287     brouard  6564:           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  6565:           cptcode = ij; /* New max modality for covar j */
                   6566:         } /* end of loop on modality i=-1 to 1 or more */
                   6567:         break;
                   6568:        case 1: /* Testing on varying covariate, could be simple and
                   6569:                * should look at waves or product of fixed *
                   6570:                * varying. No time to test -1, assuming 0 and 1 only */
                   6571:         ij=0;
                   6572:         for(i=0; i<=1;i++){
                   6573:           nbcode[Tvar[k]][++ij]=i;
                   6574:         }
                   6575:         break;
                   6576:        default:
                   6577:         break;
                   6578:        } /* end switch */
                   6579:      } /* end dummy test */
1.349     brouard  6580:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6581:        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  6582:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6583:           printf("Error k=%d \n",k);
                   6584:           exit(1);
                   6585:         }
1.311     brouard  6586:         if(isnan(covar[Tvar[k]][i])){
                   6587:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6588:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6589:           fflush(ficlog);
                   6590:           exit(1);
                   6591:          }
                   6592:        }
1.335     brouard  6593:      } /* end Quanti */
1.287     brouard  6594:    } /* 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  6595:   
                   6596:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6597:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6598:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6599:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6600:      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 */ 
                   6601:      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 */
                   6602:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6603:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6604:   
                   6605:    ij=0;
                   6606:    /* 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  6607:    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 */
                   6608:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6609:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6610:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6611:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6612:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6613:        /* 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  6614:        /* If product not in single variable we don't print results */
                   6615:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6616:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6617:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6618:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6619:        /* ij            1    2                                            3  */  
                   6620:        /* Tvaraff[ij]=  4    3                                            1  */
                   6621:        /* Tmodelind[ij]=2    3                                            9  */
                   6622:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6623:        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*/
                   6624:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6625:        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 */
                   6626:        if(Fixed[k]!=0)
                   6627:         anyvaryingduminmodel=1;
                   6628:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6629:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6630:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6631:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6632:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6633:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6634:      } 
                   6635:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6636:    /* ij--; */
                   6637:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6638:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6639:                * because they can be excluded from the model and real
                   6640:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6641:    for(j=ij+1; j<= cptcovt; j++){
                   6642:      Tvaraff[j]=0;
                   6643:      Tmodelind[j]=0;
                   6644:    }
                   6645:    for(j=ntveff+1; j<= cptcovt; j++){
                   6646:      TmodelInvind[j]=0;
                   6647:    }
                   6648:    /* To be sorted */
                   6649:    ;
                   6650:  }
1.126     brouard  6651: 
1.145     brouard  6652: 
1.126     brouard  6653: /*********** Health Expectancies ****************/
                   6654: 
1.235     brouard  6655:  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  6656: 
                   6657: {
                   6658:   /* Health expectancies, no variances */
1.329     brouard  6659:   /* cij is the combination in the list of combination of dummy covariates */
                   6660:   /* strstart is a string of time at start of computing */
1.164     brouard  6661:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6662:   int nhstepma, nstepma; /* Decreasing with age */
                   6663:   double age, agelim, hf;
                   6664:   double ***p3mat;
                   6665:   double eip;
                   6666: 
1.238     brouard  6667:   /* pstamp(ficreseij); */
1.126     brouard  6668:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6669:   fprintf(ficreseij,"# Age");
                   6670:   for(i=1; i<=nlstate;i++){
                   6671:     for(j=1; j<=nlstate;j++){
                   6672:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6673:     }
                   6674:     fprintf(ficreseij," e%1d. ",i);
                   6675:   }
                   6676:   fprintf(ficreseij,"\n");
                   6677: 
                   6678:   
                   6679:   if(estepm < stepm){
                   6680:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6681:   }
                   6682:   else  hstepm=estepm;   
                   6683:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6684:    * This is mainly to measure the difference between two models: for example
                   6685:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6686:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6687:    * progression in between and thus overestimating or underestimating according
                   6688:    * to the curvature of the survival function. If, for the same date, we 
                   6689:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6690:    * to compare the new estimate of Life expectancy with the same linear 
                   6691:    * hypothesis. A more precise result, taking into account a more precise
                   6692:    * curvature will be obtained if estepm is as small as stepm. */
                   6693: 
                   6694:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6695:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6696:      nhstepm is the number of hstepm from age to agelim 
                   6697:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6698:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6699:      and note for a fixed period like estepm months */
                   6700:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6701:      survival function given by stepm (the optimization length). Unfortunately it
                   6702:      means that if the survival funtion is printed only each two years of age and if
                   6703:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6704:      results. So we changed our mind and took the option of the best precision.
                   6705:   */
                   6706:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6707: 
                   6708:   agelim=AGESUP;
                   6709:   /* If stepm=6 months */
                   6710:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6711:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6712:     
                   6713: /* nhstepm age range expressed in number of stepm */
                   6714:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6715:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6716:   /* if (stepm >= YEARM) hstepm=1;*/
                   6717:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6718:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6719: 
                   6720:   for (age=bage; age<=fage; age ++){ 
                   6721:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6722:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6723:     /* if (stepm >= YEARM) hstepm=1;*/
                   6724:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6725: 
                   6726:     /* If stepm=6 months */
                   6727:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6728:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6729:     /* 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  6730:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6731:     
                   6732:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6733:     
                   6734:     printf("%d|",(int)age);fflush(stdout);
                   6735:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6736:     
                   6737:     /* Computing expectancies */
                   6738:     for(i=1; i<=nlstate;i++)
                   6739:       for(j=1; j<=nlstate;j++)
                   6740:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6741:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6742:          
                   6743:          /* 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]);*/
                   6744: 
                   6745:        }
                   6746: 
                   6747:     fprintf(ficreseij,"%3.0f",age );
                   6748:     for(i=1; i<=nlstate;i++){
                   6749:       eip=0;
                   6750:       for(j=1; j<=nlstate;j++){
                   6751:        eip +=eij[i][j][(int)age];
                   6752:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6753:       }
                   6754:       fprintf(ficreseij,"%9.4f", eip );
                   6755:     }
                   6756:     fprintf(ficreseij,"\n");
                   6757:     
                   6758:   }
                   6759:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6760:   printf("\n");
                   6761:   fprintf(ficlog,"\n");
                   6762:   
                   6763: }
                   6764: 
1.235     brouard  6765:  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  6766: 
                   6767: {
                   6768:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6769:      to initial status i, ei. .
1.126     brouard  6770:   */
1.336     brouard  6771:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6772:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6773:   int nhstepma, nstepma; /* Decreasing with age */
                   6774:   double age, agelim, hf;
                   6775:   double ***p3matp, ***p3matm, ***varhe;
                   6776:   double **dnewm,**doldm;
                   6777:   double *xp, *xm;
                   6778:   double **gp, **gm;
                   6779:   double ***gradg, ***trgradg;
                   6780:   int theta;
                   6781: 
                   6782:   double eip, vip;
                   6783: 
                   6784:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6785:   xp=vector(1,npar);
                   6786:   xm=vector(1,npar);
                   6787:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6788:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6789:   
                   6790:   pstamp(ficresstdeij);
                   6791:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6792:   fprintf(ficresstdeij,"# Age");
                   6793:   for(i=1; i<=nlstate;i++){
                   6794:     for(j=1; j<=nlstate;j++)
                   6795:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6796:     fprintf(ficresstdeij," e%1d. ",i);
                   6797:   }
                   6798:   fprintf(ficresstdeij,"\n");
                   6799: 
                   6800:   pstamp(ficrescveij);
                   6801:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6802:   fprintf(ficrescveij,"# Age");
                   6803:   for(i=1; i<=nlstate;i++)
                   6804:     for(j=1; j<=nlstate;j++){
                   6805:       cptj= (j-1)*nlstate+i;
                   6806:       for(i2=1; i2<=nlstate;i2++)
                   6807:        for(j2=1; j2<=nlstate;j2++){
                   6808:          cptj2= (j2-1)*nlstate+i2;
                   6809:          if(cptj2 <= cptj)
                   6810:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6811:        }
                   6812:     }
                   6813:   fprintf(ficrescveij,"\n");
                   6814:   
                   6815:   if(estepm < stepm){
                   6816:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6817:   }
                   6818:   else  hstepm=estepm;   
                   6819:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6820:    * This is mainly to measure the difference between two models: for example
                   6821:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6822:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6823:    * progression in between and thus overestimating or underestimating according
                   6824:    * to the curvature of the survival function. If, for the same date, we 
                   6825:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6826:    * to compare the new estimate of Life expectancy with the same linear 
                   6827:    * hypothesis. A more precise result, taking into account a more precise
                   6828:    * curvature will be obtained if estepm is as small as stepm. */
                   6829: 
                   6830:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6831:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6832:      nhstepm is the number of hstepm from age to agelim 
                   6833:      nstepm is the number of stepm from age to agelin. 
                   6834:      Look at hpijx to understand the reason of that which relies in memory size
                   6835:      and note for a fixed period like estepm months */
                   6836:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6837:      survival function given by stepm (the optimization length). Unfortunately it
                   6838:      means that if the survival funtion is printed only each two years of age and if
                   6839:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6840:      results. So we changed our mind and took the option of the best precision.
                   6841:   */
                   6842:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6843: 
                   6844:   /* If stepm=6 months */
                   6845:   /* nhstepm age range expressed in number of stepm */
                   6846:   agelim=AGESUP;
                   6847:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6848:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6849:   /* if (stepm >= YEARM) hstepm=1;*/
                   6850:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6851:   
                   6852:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6853:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6854:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6855:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6856:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6857:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6858: 
                   6859:   for (age=bage; age<=fage; age ++){ 
                   6860:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6861:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6862:     /* if (stepm >= YEARM) hstepm=1;*/
                   6863:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6864:                
1.126     brouard  6865:     /* If stepm=6 months */
                   6866:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6867:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6868:     
                   6869:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6870:                
1.126     brouard  6871:     /* Computing  Variances of health expectancies */
                   6872:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6873:        decrease memory allocation */
                   6874:     for(theta=1; theta <=npar; theta++){
                   6875:       for(i=1; i<=npar; i++){ 
1.222     brouard  6876:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6877:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6878:       }
1.235     brouard  6879:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6880:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6881:                        
1.126     brouard  6882:       for(j=1; j<= nlstate; j++){
1.222     brouard  6883:        for(i=1; i<=nlstate; i++){
                   6884:          for(h=0; h<=nhstepm-1; h++){
                   6885:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6886:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6887:          }
                   6888:        }
1.126     brouard  6889:       }
1.218     brouard  6890:                        
1.126     brouard  6891:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6892:        for(h=0; h<=nhstepm-1; h++){
                   6893:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6894:        }
1.126     brouard  6895:     }/* End theta */
                   6896:     
                   6897:     
                   6898:     for(h=0; h<=nhstepm-1; h++)
                   6899:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6900:        for(theta=1; theta <=npar; theta++)
                   6901:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6902:     
1.218     brouard  6903:                
1.222     brouard  6904:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6905:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6906:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6907:                
1.222     brouard  6908:     printf("%d|",(int)age);fflush(stdout);
                   6909:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6910:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6911:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6912:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6913:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6914:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6915:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6916:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6917:       }
                   6918:     }
1.320     brouard  6919:     /* if((int)age ==50){ */
                   6920:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6921:     /* } */
1.126     brouard  6922:     /* Computing expectancies */
1.235     brouard  6923:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6924:     for(i=1; i<=nlstate;i++)
                   6925:       for(j=1; j<=nlstate;j++)
1.222     brouard  6926:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6927:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6928:                                        
1.222     brouard  6929:          /* 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  6930:                                        
1.222     brouard  6931:        }
1.269     brouard  6932: 
                   6933:     /* Standard deviation of expectancies ij */                
1.126     brouard  6934:     fprintf(ficresstdeij,"%3.0f",age );
                   6935:     for(i=1; i<=nlstate;i++){
                   6936:       eip=0.;
                   6937:       vip=0.;
                   6938:       for(j=1; j<=nlstate;j++){
1.222     brouard  6939:        eip += eij[i][j][(int)age];
                   6940:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6941:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6942:        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  6943:       }
                   6944:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6945:     }
                   6946:     fprintf(ficresstdeij,"\n");
1.218     brouard  6947:                
1.269     brouard  6948:     /* Variance of expectancies ij */          
1.126     brouard  6949:     fprintf(ficrescveij,"%3.0f",age );
                   6950:     for(i=1; i<=nlstate;i++)
                   6951:       for(j=1; j<=nlstate;j++){
1.222     brouard  6952:        cptj= (j-1)*nlstate+i;
                   6953:        for(i2=1; i2<=nlstate;i2++)
                   6954:          for(j2=1; j2<=nlstate;j2++){
                   6955:            cptj2= (j2-1)*nlstate+i2;
                   6956:            if(cptj2 <= cptj)
                   6957:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6958:          }
1.126     brouard  6959:       }
                   6960:     fprintf(ficrescveij,"\n");
1.218     brouard  6961:                
1.126     brouard  6962:   }
                   6963:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6964:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6965:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6966:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6967:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6968:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6969:   printf("\n");
                   6970:   fprintf(ficlog,"\n");
1.218     brouard  6971:        
1.126     brouard  6972:   free_vector(xm,1,npar);
                   6973:   free_vector(xp,1,npar);
                   6974:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6975:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6976:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6977: }
1.218     brouard  6978:  
1.126     brouard  6979: /************ Variance ******************/
1.235     brouard  6980:  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  6981:  {
1.279     brouard  6982:    /** Variance of health expectancies 
                   6983:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6984:     * double **newm;
                   6985:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6986:     */
1.218     brouard  6987:   
                   6988:    /* int movingaverage(); */
                   6989:    double **dnewm,**doldm;
                   6990:    double **dnewmp,**doldmp;
                   6991:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6992:    int first=0;
1.218     brouard  6993:    int k;
                   6994:    double *xp;
1.279     brouard  6995:    double **gp, **gm;  /**< for var eij */
                   6996:    double ***gradg, ***trgradg; /**< for var eij */
                   6997:    double **gradgp, **trgradgp; /**< for var p point j */
                   6998:    double *gpp, *gmp; /**< for var p point j */
                   6999:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7000:    double ***p3mat;
                   7001:    double age,agelim, hf;
                   7002:    /* double ***mobaverage; */
                   7003:    int theta;
                   7004:    char digit[4];
                   7005:    char digitp[25];
                   7006: 
                   7007:    char fileresprobmorprev[FILENAMELENGTH];
                   7008: 
                   7009:    if(popbased==1){
                   7010:      if(mobilav!=0)
                   7011:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7012:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7013:    }
                   7014:    else 
                   7015:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7016: 
1.218     brouard  7017:    /* if (mobilav!=0) { */
                   7018:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7019:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7020:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7021:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7022:    /*   } */
                   7023:    /* } */
                   7024: 
                   7025:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7026:    sprintf(digit,"%-d",ij);
                   7027:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7028:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7029:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7030:    strcat(fileresprobmorprev,fileresu);
                   7031:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7032:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7033:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7034:    }
                   7035:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7036:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7037:    pstamp(ficresprobmorprev);
                   7038:    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  7039:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7040: 
                   7041:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7042:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7043:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7044:    /* } */
                   7045:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7046:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7047:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7048:    }
1.337     brouard  7049:    /* for(j=1;j<=cptcoveff;j++)  */
                   7050:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7051:    fprintf(ficresprobmorprev,"\n");
                   7052: 
1.218     brouard  7053:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7054:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7055:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7056:      for(i=1; i<=nlstate;i++)
                   7057:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7058:    }  
                   7059:    fprintf(ficresprobmorprev,"\n");
                   7060:   
                   7061:    fprintf(ficgp,"\n# Routine varevsij");
                   7062:    fprintf(ficgp,"\nunset title \n");
                   7063:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7064:    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");
                   7065:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7066: 
1.218     brouard  7067:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7068:    pstamp(ficresvij);
                   7069:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7070:    if(popbased==1)
                   7071:      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);
                   7072:    else
                   7073:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7074:    fprintf(ficresvij,"# Age");
                   7075:    for(i=1; i<=nlstate;i++)
                   7076:      for(j=1; j<=nlstate;j++)
                   7077:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7078:    fprintf(ficresvij,"\n");
                   7079: 
                   7080:    xp=vector(1,npar);
                   7081:    dnewm=matrix(1,nlstate,1,npar);
                   7082:    doldm=matrix(1,nlstate,1,nlstate);
                   7083:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7084:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7085: 
                   7086:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7087:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7088:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7089:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7090:   
1.218     brouard  7091:    if(estepm < stepm){
                   7092:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7093:    }
                   7094:    else  hstepm=estepm;   
                   7095:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7096:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7097:       nhstepm is the number of hstepm from age to agelim 
                   7098:       nstepm is the number of stepm from age to agelim. 
                   7099:       Look at function hpijx to understand why because of memory size limitations, 
                   7100:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7101:       survival function given by stepm (the optimization length). Unfortunately it
                   7102:       means that if the survival funtion is printed every two years of age and if
                   7103:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7104:       results. So we changed our mind and took the option of the best precision.
                   7105:    */
                   7106:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7107:    agelim = AGESUP;
                   7108:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7109:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7110:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7111:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7112:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7113:      gp=matrix(0,nhstepm,1,nlstate);
                   7114:      gm=matrix(0,nhstepm,1,nlstate);
                   7115:                
                   7116:                
                   7117:      for(theta=1; theta <=npar; theta++){
                   7118:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7119:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7120:        }
1.279     brouard  7121:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7122:        * returns into prlim .
1.288     brouard  7123:        */
1.242     brouard  7124:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7125: 
                   7126:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7127:        if (popbased==1) {
                   7128:         if(mobilav ==0){
                   7129:           for(i=1; i<=nlstate;i++)
                   7130:             prlim[i][i]=probs[(int)age][i][ij];
                   7131:         }else{ /* mobilav */ 
                   7132:           for(i=1; i<=nlstate;i++)
                   7133:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7134:         }
                   7135:        }
1.295     brouard  7136:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7137:        */                      
                   7138:        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  7139:        /**< 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  7140:        * at horizon h in state j including mortality.
                   7141:        */
1.218     brouard  7142:        for(j=1; j<= nlstate; j++){
                   7143:         for(h=0; h<=nhstepm; h++){
                   7144:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7145:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7146:         }
                   7147:        }
1.279     brouard  7148:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7149:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7150:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7151:        */
                   7152:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7153:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7154:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7155:        }
                   7156:        
                   7157:        /* Again with minus shift */
1.218     brouard  7158:                        
                   7159:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7160:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7161: 
1.242     brouard  7162:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7163:                        
                   7164:        if (popbased==1) {
                   7165:         if(mobilav ==0){
                   7166:           for(i=1; i<=nlstate;i++)
                   7167:             prlim[i][i]=probs[(int)age][i][ij];
                   7168:         }else{ /* mobilav */ 
                   7169:           for(i=1; i<=nlstate;i++)
                   7170:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7171:         }
                   7172:        }
                   7173:                        
1.235     brouard  7174:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7175:                        
                   7176:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7177:         for(h=0; h<=nhstepm; h++){
                   7178:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7179:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7180:         }
                   7181:        }
                   7182:        /* This for computing probability of death (h=1 means
                   7183:          computed over hstepm matrices product = hstepm*stepm months) 
                   7184:          as a weighted average of prlim.
                   7185:        */
                   7186:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7187:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7188:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7189:        }    
1.279     brouard  7190:        /* end shifting computations */
                   7191: 
                   7192:        /**< Computing gradient matrix at horizon h 
                   7193:        */
1.218     brouard  7194:        for(j=1; j<= nlstate; j++) /* vareij */
                   7195:         for(h=0; h<=nhstepm; h++){
                   7196:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7197:         }
1.279     brouard  7198:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7199:        */
                   7200:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7201:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7202:        }
                   7203:                        
                   7204:      } /* End theta */
1.279     brouard  7205:      
                   7206:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7207:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7208:                
                   7209:      for(h=0; h<=nhstepm; h++) /* veij */
                   7210:        for(j=1; j<=nlstate;j++)
                   7211:         for(theta=1; theta <=npar; theta++)
                   7212:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7213:                
                   7214:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7215:        for(theta=1; theta <=npar; theta++)
                   7216:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7217:      /**< as well as its transposed matrix 
                   7218:       */               
1.218     brouard  7219:                
                   7220:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7221:      for(i=1;i<=nlstate;i++)
                   7222:        for(j=1;j<=nlstate;j++)
                   7223:         vareij[i][j][(int)age] =0.;
1.279     brouard  7224: 
                   7225:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7226:       * and k (nhstepm) formula 15 of article
                   7227:       * Lievre-Brouard-Heathcote
                   7228:       */
                   7229:      
1.218     brouard  7230:      for(h=0;h<=nhstepm;h++){
                   7231:        for(k=0;k<=nhstepm;k++){
                   7232:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7233:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7234:         for(i=1;i<=nlstate;i++)
                   7235:           for(j=1;j<=nlstate;j++)
                   7236:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7237:        }
                   7238:      }
                   7239:                
1.279     brouard  7240:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7241:       * p.j overall mortality formula 49 but computed directly because
                   7242:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7243:       * wix is independent of theta.
                   7244:       */
1.218     brouard  7245:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7246:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7247:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7248:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7249:         varppt[j][i]=doldmp[j][i];
                   7250:      /* end ppptj */
                   7251:      /*  x centered again */
                   7252:                
1.242     brouard  7253:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7254:                
                   7255:      if (popbased==1) {
                   7256:        if(mobilav ==0){
                   7257:         for(i=1; i<=nlstate;i++)
                   7258:           prlim[i][i]=probs[(int)age][i][ij];
                   7259:        }else{ /* mobilav */ 
                   7260:         for(i=1; i<=nlstate;i++)
                   7261:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7262:        }
                   7263:      }
                   7264:                
                   7265:      /* This for computing probability of death (h=1 means
                   7266:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7267:        as a weighted average of prlim.
                   7268:      */
1.235     brouard  7269:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7270:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7271:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7272:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7273:      }    
                   7274:      /* end probability of death */
                   7275:                
                   7276:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7277:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7278:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7279:        for(i=1; i<=nlstate;i++){
                   7280:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7281:        }
                   7282:      } 
                   7283:      fprintf(ficresprobmorprev,"\n");
                   7284:                
                   7285:      fprintf(ficresvij,"%.0f ",age );
                   7286:      for(i=1; i<=nlstate;i++)
                   7287:        for(j=1; j<=nlstate;j++){
                   7288:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7289:        }
                   7290:      fprintf(ficresvij,"\n");
                   7291:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7292:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7293:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7294:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7295:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7296:    } /* End age */
                   7297:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7298:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7299:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7300:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7301:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7302:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7303:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7304:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7305:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7306:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7307:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7308:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7309:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7310:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7311:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7312:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7313:    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);
                   7314:    /*  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  7315:     */
1.218     brouard  7316:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7317:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7318: 
1.218     brouard  7319:    free_vector(xp,1,npar);
                   7320:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7321:    free_matrix(dnewm,1,nlstate,1,npar);
                   7322:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7323:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7324:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7325:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7326:    fclose(ficresprobmorprev);
                   7327:    fflush(ficgp);
                   7328:    fflush(fichtm); 
                   7329:  }  /* end varevsij */
1.126     brouard  7330: 
                   7331: /************ Variance of prevlim ******************/
1.269     brouard  7332:  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  7333: {
1.205     brouard  7334:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7335:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7336: 
1.268     brouard  7337:   double **dnewmpar,**doldm;
1.126     brouard  7338:   int i, j, nhstepm, hstepm;
                   7339:   double *xp;
                   7340:   double *gp, *gm;
                   7341:   double **gradg, **trgradg;
1.208     brouard  7342:   double **mgm, **mgp;
1.126     brouard  7343:   double age,agelim;
                   7344:   int theta;
                   7345:   
                   7346:   pstamp(ficresvpl);
1.288     brouard  7347:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7348:   fprintf(ficresvpl,"# Age ");
                   7349:   if(nresult >=1)
                   7350:     fprintf(ficresvpl," Result# ");
1.126     brouard  7351:   for(i=1; i<=nlstate;i++)
                   7352:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7353:   fprintf(ficresvpl,"\n");
                   7354: 
                   7355:   xp=vector(1,npar);
1.268     brouard  7356:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7357:   doldm=matrix(1,nlstate,1,nlstate);
                   7358:   
                   7359:   hstepm=1*YEARM; /* Every year of age */
                   7360:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7361:   agelim = AGESUP;
                   7362:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7363:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7364:     if (stepm >= YEARM) hstepm=1;
                   7365:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7366:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7367:     mgp=matrix(1,npar,1,nlstate);
                   7368:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7369:     gp=vector(1,nlstate);
                   7370:     gm=vector(1,nlstate);
                   7371: 
                   7372:     for(theta=1; theta <=npar; theta++){
                   7373:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7374:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7375:       }
1.288     brouard  7376:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7377:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7378:       /* else */
                   7379:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7380:       for(i=1;i<=nlstate;i++){
1.126     brouard  7381:        gp[i] = prlim[i][i];
1.208     brouard  7382:        mgp[theta][i] = prlim[i][i];
                   7383:       }
1.126     brouard  7384:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7385:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7386:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7387:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7388:       /* else */
                   7389:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7390:       for(i=1;i<=nlstate;i++){
1.126     brouard  7391:        gm[i] = prlim[i][i];
1.208     brouard  7392:        mgm[theta][i] = prlim[i][i];
                   7393:       }
1.126     brouard  7394:       for(i=1;i<=nlstate;i++)
                   7395:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7396:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7397:     } /* End theta */
                   7398: 
                   7399:     trgradg =matrix(1,nlstate,1,npar);
                   7400: 
                   7401:     for(j=1; j<=nlstate;j++)
                   7402:       for(theta=1; theta <=npar; theta++)
                   7403:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7404:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7405:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7406:     /*   for(j=1; j<=nlstate;j++){ */
                   7407:     /*         printf(" %d ",j); */
                   7408:     /*         for(theta=1; theta <=npar; theta++) */
                   7409:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7410:     /*         printf("\n "); */
                   7411:     /*   } */
                   7412:     /* } */
                   7413:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7414:     /*   printf("\n gradg %d ",(int)age); */
                   7415:     /*   for(j=1; j<=nlstate;j++){ */
                   7416:     /*         printf("%d ",j); */
                   7417:     /*         for(theta=1; theta <=npar; theta++) */
                   7418:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7419:     /*         printf("\n "); */
                   7420:     /*   } */
                   7421:     /* } */
1.126     brouard  7422: 
                   7423:     for(i=1;i<=nlstate;i++)
                   7424:       varpl[i][(int)age] =0.;
1.209     brouard  7425:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7426:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7427:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7428:     }else{
1.268     brouard  7429:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7430:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7431:     }
1.126     brouard  7432:     for(i=1;i<=nlstate;i++)
                   7433:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7434: 
                   7435:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7436:     if(nresult >=1)
                   7437:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7438:     for(i=1; i<=nlstate;i++){
1.126     brouard  7439:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7440:       /* for(j=1;j<=nlstate;j++) */
                   7441:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7442:     }
1.126     brouard  7443:     fprintf(ficresvpl,"\n");
                   7444:     free_vector(gp,1,nlstate);
                   7445:     free_vector(gm,1,nlstate);
1.208     brouard  7446:     free_matrix(mgm,1,npar,1,nlstate);
                   7447:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7448:     free_matrix(gradg,1,npar,1,nlstate);
                   7449:     free_matrix(trgradg,1,nlstate,1,npar);
                   7450:   } /* End age */
                   7451: 
                   7452:   free_vector(xp,1,npar);
                   7453:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7454:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7455: 
                   7456: }
                   7457: 
                   7458: 
                   7459: /************ Variance of backprevalence limit ******************/
1.269     brouard  7460:  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  7461: {
                   7462:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7463:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7464: 
                   7465:   double **dnewmpar,**doldm;
                   7466:   int i, j, nhstepm, hstepm;
                   7467:   double *xp;
                   7468:   double *gp, *gm;
                   7469:   double **gradg, **trgradg;
                   7470:   double **mgm, **mgp;
                   7471:   double age,agelim;
                   7472:   int theta;
                   7473:   
                   7474:   pstamp(ficresvbl);
                   7475:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7476:   fprintf(ficresvbl,"# Age ");
                   7477:   if(nresult >=1)
                   7478:     fprintf(ficresvbl," Result# ");
                   7479:   for(i=1; i<=nlstate;i++)
                   7480:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7481:   fprintf(ficresvbl,"\n");
                   7482: 
                   7483:   xp=vector(1,npar);
                   7484:   dnewmpar=matrix(1,nlstate,1,npar);
                   7485:   doldm=matrix(1,nlstate,1,nlstate);
                   7486:   
                   7487:   hstepm=1*YEARM; /* Every year of age */
                   7488:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7489:   agelim = AGEINF;
                   7490:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7491:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7492:     if (stepm >= YEARM) hstepm=1;
                   7493:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7494:     gradg=matrix(1,npar,1,nlstate);
                   7495:     mgp=matrix(1,npar,1,nlstate);
                   7496:     mgm=matrix(1,npar,1,nlstate);
                   7497:     gp=vector(1,nlstate);
                   7498:     gm=vector(1,nlstate);
                   7499: 
                   7500:     for(theta=1; theta <=npar; theta++){
                   7501:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7502:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7503:       }
                   7504:       if(mobilavproj > 0 )
                   7505:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7506:       else
                   7507:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7508:       for(i=1;i<=nlstate;i++){
                   7509:        gp[i] = bprlim[i][i];
                   7510:        mgp[theta][i] = bprlim[i][i];
                   7511:       }
                   7512:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7513:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7514:        if(mobilavproj > 0 )
                   7515:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7516:        else
                   7517:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7518:       for(i=1;i<=nlstate;i++){
                   7519:        gm[i] = bprlim[i][i];
                   7520:        mgm[theta][i] = bprlim[i][i];
                   7521:       }
                   7522:       for(i=1;i<=nlstate;i++)
                   7523:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7524:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7525:     } /* End theta */
                   7526: 
                   7527:     trgradg =matrix(1,nlstate,1,npar);
                   7528: 
                   7529:     for(j=1; j<=nlstate;j++)
                   7530:       for(theta=1; theta <=npar; theta++)
                   7531:        trgradg[j][theta]=gradg[theta][j];
                   7532:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7533:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7534:     /*   for(j=1; j<=nlstate;j++){ */
                   7535:     /*         printf(" %d ",j); */
                   7536:     /*         for(theta=1; theta <=npar; theta++) */
                   7537:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7538:     /*         printf("\n "); */
                   7539:     /*   } */
                   7540:     /* } */
                   7541:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7542:     /*   printf("\n gradg %d ",(int)age); */
                   7543:     /*   for(j=1; j<=nlstate;j++){ */
                   7544:     /*         printf("%d ",j); */
                   7545:     /*         for(theta=1; theta <=npar; theta++) */
                   7546:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7547:     /*         printf("\n "); */
                   7548:     /*   } */
                   7549:     /* } */
                   7550: 
                   7551:     for(i=1;i<=nlstate;i++)
                   7552:       varbpl[i][(int)age] =0.;
                   7553:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7554:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7555:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7556:     }else{
                   7557:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7558:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7559:     }
                   7560:     for(i=1;i<=nlstate;i++)
                   7561:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7562: 
                   7563:     fprintf(ficresvbl,"%.0f ",age );
                   7564:     if(nresult >=1)
                   7565:       fprintf(ficresvbl,"%d ",nres );
                   7566:     for(i=1; i<=nlstate;i++)
                   7567:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7568:     fprintf(ficresvbl,"\n");
                   7569:     free_vector(gp,1,nlstate);
                   7570:     free_vector(gm,1,nlstate);
                   7571:     free_matrix(mgm,1,npar,1,nlstate);
                   7572:     free_matrix(mgp,1,npar,1,nlstate);
                   7573:     free_matrix(gradg,1,npar,1,nlstate);
                   7574:     free_matrix(trgradg,1,nlstate,1,npar);
                   7575:   } /* End age */
                   7576: 
                   7577:   free_vector(xp,1,npar);
                   7578:   free_matrix(doldm,1,nlstate,1,npar);
                   7579:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7580: 
                   7581: }
                   7582: 
                   7583: /************ Variance of one-step probabilities  ******************/
                   7584: 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  7585:  {
                   7586:    int i, j=0,  k1, l1, tj;
                   7587:    int k2, l2, j1,  z1;
                   7588:    int k=0, l;
                   7589:    int first=1, first1, first2;
1.326     brouard  7590:    int nres=0; /* New */
1.222     brouard  7591:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7592:    double **dnewm,**doldm;
                   7593:    double *xp;
                   7594:    double *gp, *gm;
                   7595:    double **gradg, **trgradg;
                   7596:    double **mu;
                   7597:    double age, cov[NCOVMAX+1];
                   7598:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7599:    int theta;
                   7600:    char fileresprob[FILENAMELENGTH];
                   7601:    char fileresprobcov[FILENAMELENGTH];
                   7602:    char fileresprobcor[FILENAMELENGTH];
                   7603:    double ***varpij;
                   7604: 
                   7605:    strcpy(fileresprob,"PROB_"); 
                   7606:    strcat(fileresprob,fileres);
                   7607:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7608:      printf("Problem with resultfile: %s\n", fileresprob);
                   7609:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7610:    }
                   7611:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7612:    strcat(fileresprobcov,fileresu);
                   7613:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7614:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7615:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7616:    }
                   7617:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7618:    strcat(fileresprobcor,fileresu);
                   7619:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7620:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7621:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7622:    }
                   7623:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7624:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7625:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7626:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7627:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7628:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7629:    pstamp(ficresprob);
                   7630:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7631:    fprintf(ficresprob,"# Age");
                   7632:    pstamp(ficresprobcov);
                   7633:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7634:    fprintf(ficresprobcov,"# Age");
                   7635:    pstamp(ficresprobcor);
                   7636:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7637:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7638: 
                   7639: 
1.222     brouard  7640:    for(i=1; i<=nlstate;i++)
                   7641:      for(j=1; j<=(nlstate+ndeath);j++){
                   7642:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7643:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7644:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7645:      }  
                   7646:    /* fprintf(ficresprob,"\n");
                   7647:       fprintf(ficresprobcov,"\n");
                   7648:       fprintf(ficresprobcor,"\n");
                   7649:    */
                   7650:    xp=vector(1,npar);
                   7651:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7652:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7653:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7654:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7655:    first=1;
                   7656:    fprintf(ficgp,"\n# Routine varprob");
                   7657:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7658:    fprintf(fichtm,"\n");
                   7659: 
1.288     brouard  7660:    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  7661:    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);
                   7662:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7663: and drawn. It helps understanding how is the covariance between two incidences.\
                   7664:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7665:    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  7666: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7667: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7668: standard deviations wide on each axis. <br>\
                   7669:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7670:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7671: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7672: 
1.222     brouard  7673:    cov[1]=1;
                   7674:    /* tj=cptcoveff; */
1.225     brouard  7675:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7676:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7677:    j1=0;
1.332     brouard  7678: 
                   7679:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7680:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7681:      /* 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  7682:      if(tj != 1 && TKresult[nres]!= j1)
                   7683:        continue;
                   7684: 
                   7685:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7686:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7687:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7688:      if  (cptcovn>0) {
1.334     brouard  7689:        fprintf(ficresprob, "\n#********** Variable ");
                   7690:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7691:        fprintf(ficgp, "\n#********** Variable ");
                   7692:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7693:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7694: 
                   7695:        /* Including quantitative variables of the resultline to be done */
                   7696:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7697:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7698:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7699:         /* 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  7700:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7701:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7702:             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  */
                   7703:             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  */
                   7704:             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  */
                   7705:             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  */
                   7706:             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  */
                   7707:             fprintf(ficresprob,"fixed ");
                   7708:             fprintf(ficresprobcov,"fixed ");
                   7709:             fprintf(ficgp,"fixed ");
                   7710:             fprintf(fichtmcov,"fixed ");
                   7711:             fprintf(ficresprobcor,"fixed ");
                   7712:           }else{
                   7713:             fprintf(ficresprob,"varyi ");
                   7714:             fprintf(ficresprobcov,"varyi ");
                   7715:             fprintf(ficgp,"varyi ");
                   7716:             fprintf(fichtmcov,"varyi ");
                   7717:             fprintf(ficresprobcor,"varyi ");
                   7718:           }
                   7719:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7720:           /* For each selected (single) quantitative value */
1.337     brouard  7721:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7722:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7723:             fprintf(ficresprob,"fixed ");
                   7724:             fprintf(ficresprobcov,"fixed ");
                   7725:             fprintf(ficgp,"fixed ");
                   7726:             fprintf(fichtmcov,"fixed ");
                   7727:             fprintf(ficresprobcor,"fixed ");
                   7728:           }else{
                   7729:             fprintf(ficresprob,"varyi ");
                   7730:             fprintf(ficresprobcov,"varyi ");
                   7731:             fprintf(ficgp,"varyi ");
                   7732:             fprintf(fichtmcov,"varyi ");
                   7733:             fprintf(ficresprobcor,"varyi ");
                   7734:           }
                   7735:         }else{
                   7736:           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 */
                   7737:           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 */
                   7738:           exit(1);
                   7739:         }
                   7740:        } /* End loop on variable of this resultline */
                   7741:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7742:        fprintf(ficresprob, "**********\n#\n");
                   7743:        fprintf(ficresprobcov, "**********\n#\n");
                   7744:        fprintf(ficgp, "**********\n#\n");
                   7745:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7746:        fprintf(ficresprobcor, "**********\n#");    
                   7747:        if(invalidvarcomb[j1]){
                   7748:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7749:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7750:         continue;
                   7751:        }
                   7752:      }
                   7753:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7754:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7755:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7756:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7757:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7758:        cov[2]=age;
                   7759:        if(nagesqr==1)
                   7760:         cov[3]= age*age;
1.334     brouard  7761:        /* New code end of combination but for each resultline */
                   7762:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7763:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7764:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7765:         }else{
1.334     brouard  7766:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7767:         }
1.334     brouard  7768:        }/* End of loop on model equation */
                   7769: /* Old code */
                   7770:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7771:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7772:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7773:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7774:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7775:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7776:        /*                                                                  * 1  1 1 1 1 */
                   7777:        /*                                                                  * 2  2 1 1 1 */
                   7778:        /*                                                                  * 3  1 2 1 1 */
                   7779:        /*                                                                  *\/ */
                   7780:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7781:        /* } */
                   7782:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7783:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7784:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7785:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7786:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7787:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7788:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7789:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7790:        /*         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]); */
                   7791:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7792:        /*         /\* exit(1); *\/ */
                   7793:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7794:        /*       } */
                   7795:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7796:        /* } */
                   7797:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7798:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7799:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7800:        /*           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]])]; */
                   7801:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7802:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7803:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7804:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7805:        /*         } */
                   7806:        /*       }else{ */
                   7807:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7808:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7809:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7810:        /*         }else{ */
                   7811:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7812:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7813:        /*         } */
                   7814:        /*       } */
                   7815:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7816:        /* } */                 
1.326     brouard  7817: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7818:        for(theta=1; theta <=npar; theta++){
                   7819:         for(i=1; i<=npar; i++)
                   7820:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7821:                                
1.222     brouard  7822:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7823:                                
1.222     brouard  7824:         k=0;
                   7825:         for(i=1; i<= (nlstate); i++){
                   7826:           for(j=1; j<=(nlstate+ndeath);j++){
                   7827:             k=k+1;
                   7828:             gp[k]=pmmij[i][j];
                   7829:           }
                   7830:         }
1.220     brouard  7831:                                
1.222     brouard  7832:         for(i=1; i<=npar; i++)
                   7833:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7834:                                
1.222     brouard  7835:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7836:         k=0;
                   7837:         for(i=1; i<=(nlstate); i++){
                   7838:           for(j=1; j<=(nlstate+ndeath);j++){
                   7839:             k=k+1;
                   7840:             gm[k]=pmmij[i][j];
                   7841:           }
                   7842:         }
1.220     brouard  7843:                                
1.222     brouard  7844:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7845:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7846:        }
1.126     brouard  7847: 
1.222     brouard  7848:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7849:         for(theta=1; theta <=npar; theta++)
                   7850:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7851:                        
1.222     brouard  7852:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7853:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7854:                        
1.222     brouard  7855:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7856:                        
1.222     brouard  7857:        k=0;
                   7858:        for(i=1; i<=(nlstate); i++){
                   7859:         for(j=1; j<=(nlstate+ndeath);j++){
                   7860:           k=k+1;
                   7861:           mu[k][(int) age]=pmmij[i][j];
                   7862:         }
                   7863:        }
                   7864:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7865:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7866:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7867:                        
1.222     brouard  7868:        /*printf("\n%d ",(int)age);
                   7869:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7870:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7871:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7872:         }*/
1.220     brouard  7873:                        
1.222     brouard  7874:        fprintf(ficresprob,"\n%d ",(int)age);
                   7875:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7876:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7877:                        
1.222     brouard  7878:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7879:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7880:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7881:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7882:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7883:        }
                   7884:        i=0;
                   7885:        for (k=1; k<=(nlstate);k++){
                   7886:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7887:           i++;
                   7888:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7889:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7890:           for (j=1; j<=i;j++){
                   7891:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7892:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7893:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7894:           }
                   7895:         }
                   7896:        }/* end of loop for state */
                   7897:      } /* end of loop for age */
                   7898:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7899:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7900:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7901:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7902:     
                   7903:      /* Confidence intervalle of pij  */
                   7904:      /*
                   7905:        fprintf(ficgp,"\nunset parametric;unset label");
                   7906:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7907:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7908:        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);
                   7909:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7910:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7911:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7912:      */
                   7913:                
                   7914:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7915:      first1=1;first2=2;
                   7916:      for (k2=1; k2<=(nlstate);k2++){
                   7917:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7918:         if(l2==k2) continue;
                   7919:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7920:         for (k1=1; k1<=(nlstate);k1++){
                   7921:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7922:             if(l1==k1) continue;
                   7923:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7924:             if(i<=j) continue;
                   7925:             for (age=bage; age<=fage; age ++){ 
                   7926:               if ((int)age %5==0){
                   7927:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7928:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7929:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7930:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7931:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7932:                 c12=cv12/sqrt(v1*v2);
                   7933:                 /* Computing eigen value of matrix of covariance */
                   7934:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7935:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7936:                 if ((lc2 <0) || (lc1 <0) ){
                   7937:                   if(first2==1){
                   7938:                     first1=0;
                   7939:                     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);
                   7940:                   }
                   7941:                   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);
                   7942:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7943:                   /* lc2=fabs(lc2); */
                   7944:                 }
1.220     brouard  7945:                                                                
1.222     brouard  7946:                 /* Eigen vectors */
1.280     brouard  7947:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7948:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7949:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7950:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7951:                 }else
                   7952:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7953:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7954:                 v21=(lc1-v1)/cv12*v11;
                   7955:                 v12=-v21;
                   7956:                 v22=v11;
                   7957:                 tnalp=v21/v11;
                   7958:                 if(first1==1){
                   7959:                   first1=0;
                   7960:                   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);
                   7961:                 }
                   7962:                 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);
                   7963:                 /*printf(fignu*/
                   7964:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7965:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7966:                 if(first==1){
                   7967:                   first=0;
                   7968:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7969:                   fprintf(ficgp,"\nset parametric;unset label");
                   7970:                   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);
                   7971:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7972:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7973:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7974: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7975:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7976:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7977:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7978:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7979:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7980:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7981:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7982:                   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  7983:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7984:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7985:                 }else{
                   7986:                   first=0;
                   7987:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7988:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7989:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7990:                   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  7991:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7992:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7993:                 }/* if first */
                   7994:               } /* age mod 5 */
                   7995:             } /* end loop age */
                   7996:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7997:             first=1;
                   7998:           } /*l12 */
                   7999:         } /* k12 */
                   8000:        } /*l1 */
                   8001:      }/* k1 */
1.332     brouard  8002:    }  /* loop on combination of covariates j1 */
1.326     brouard  8003:    } /* loop on nres */
1.222     brouard  8004:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8005:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8006:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8007:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8008:    free_vector(xp,1,npar);
                   8009:    fclose(ficresprob);
                   8010:    fclose(ficresprobcov);
                   8011:    fclose(ficresprobcor);
                   8012:    fflush(ficgp);
                   8013:    fflush(fichtmcov);
                   8014:  }
1.126     brouard  8015: 
                   8016: 
                   8017: /******************* Printing html file ***********/
1.201     brouard  8018: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8019:                  int lastpass, int stepm, int weightopt, char model[],\
                   8020:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8021:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8022:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8023:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8024:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8025:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8026:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8027:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8028: </ul>");
1.319     brouard  8029: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8030: /* </ul>", model); */
1.214     brouard  8031:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8032:    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",
                   8033:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8034:    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  8035:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8036:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8037:    fprintf(fichtm,"\
                   8038:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8039:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8040:    fprintf(fichtm,"\
1.217     brouard  8041:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8042:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8043:    fprintf(fichtm,"\
1.288     brouard  8044:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8045:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8046:    fprintf(fichtm,"\
1.288     brouard  8047:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8048:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8049:    fprintf(fichtm,"\
1.211     brouard  8050:  - (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  8051:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8052:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8053:    if(prevfcast==1){
                   8054:      fprintf(fichtm,"\
                   8055:  - Prevalence projections by age and states:                           \
1.201     brouard  8056:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8057:    }
1.126     brouard  8058: 
                   8059: 
1.225     brouard  8060:    m=pow(2,cptcoveff);
1.222     brouard  8061:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8062: 
1.317     brouard  8063:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8064: 
                   8065:    jj1=0;
                   8066: 
                   8067:    fprintf(fichtm," \n<ul>");
1.337     brouard  8068:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8069:      /* k1=nres; */
1.338     brouard  8070:      k1=TKresult[nres];
                   8071:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8072:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8073:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8074:    /*     continue; */
1.264     brouard  8075:      jj1++;
                   8076:      if (cptcovn > 0) {
                   8077:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8078:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8079:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8080:        }
1.337     brouard  8081:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8082:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8083:        /* } */
                   8084:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8085:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8086:        /* } */
1.264     brouard  8087:        fprintf(fichtm,"\">");
                   8088:        
                   8089:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8090:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8091:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8092:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8093:        }
1.337     brouard  8094:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8095:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8096:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8097:        /* } */
                   8098:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8099:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8100:        /* } */
1.264     brouard  8101:        if(invalidvarcomb[k1]){
                   8102:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8103:         continue;
                   8104:        }
                   8105:        fprintf(fichtm,"</a></li>");
                   8106:      } /* cptcovn >0 */
                   8107:    }
1.317     brouard  8108:    fprintf(fichtm," \n</ul>");
1.264     brouard  8109: 
1.222     brouard  8110:    jj1=0;
1.237     brouard  8111: 
1.337     brouard  8112:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8113:      /* k1=nres; */
1.338     brouard  8114:      k1=TKresult[nres];
                   8115:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8116:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8117:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8118:    /*     continue; */
1.220     brouard  8119: 
1.222     brouard  8120:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8121:      jj1++;
                   8122:      if (cptcovn > 0) {
1.264     brouard  8123:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8124:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8125:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8126:        }
1.337     brouard  8127:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8128:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8129:        /* } */
1.264     brouard  8130:        fprintf(fichtm,"\"</a>");
                   8131:  
1.222     brouard  8132:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8133:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8134:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8135:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8136:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8137:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8138:        }
1.230     brouard  8139:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8140:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8141:        if(invalidvarcomb[k1]){
                   8142:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8143:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8144:         continue;
                   8145:        }
                   8146:      }
                   8147:      /* aij, bij */
1.259     brouard  8148:      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  8149: <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  8150:      /* Pij */
1.241     brouard  8151:      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> \
                   8152: <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  8153:      /* Quasi-incidences */
                   8154:      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  8155:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8156:  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  8157: 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> \
                   8158: <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  8159:      /* Survival functions (period) in state j */
                   8160:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8161:        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);
                   8162:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8163:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8164:      }
                   8165:      /* State specific survival functions (period) */
                   8166:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8167:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8168:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8169:  <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);
                   8170:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8171:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8172:      }
1.288     brouard  8173:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8174:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8175:        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  8176:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8177:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8178:      }
1.296     brouard  8179:      if(prevbcast==1){
1.288     brouard  8180:        /* Backward prevalence in each health state */
1.222     brouard  8181:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8182:         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);
                   8183:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8184:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8185:        }
1.217     brouard  8186:      }
1.222     brouard  8187:      if(prevfcast==1){
1.288     brouard  8188:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8189:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8190:         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);
                   8191:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8192:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8193:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8194:        }
                   8195:      }
1.296     brouard  8196:      if(prevbcast==1){
1.268     brouard  8197:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8198:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8199:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8200:  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 \
                   8201:  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  8202: 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);
                   8203:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8204:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8205:        }
                   8206:      }
1.220     brouard  8207:         
1.222     brouard  8208:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8209:        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);
                   8210:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8211:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8212:      }
                   8213:      /* } /\* end i1 *\/ */
1.337     brouard  8214:    }/* End k1=nres */
1.222     brouard  8215:    fprintf(fichtm,"</ul>");
1.126     brouard  8216: 
1.222     brouard  8217:    fprintf(fichtm,"\
1.126     brouard  8218: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8219:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8220:  - 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  8221: But because parameters are usually highly correlated (a higher incidence of disability \
                   8222: and a higher incidence of recovery can give very close observed transition) it might \
                   8223: be very useful to look not only at linear confidence intervals estimated from the \
                   8224: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8225: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8226: covariance matrix of the one-step probabilities. \
                   8227: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8228: 
1.222     brouard  8229:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8230:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8231:    fprintf(fichtm,"\
1.126     brouard  8232:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8233:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8234: 
1.222     brouard  8235:    fprintf(fichtm,"\
1.126     brouard  8236:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8237:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8238:    fprintf(fichtm,"\
1.126     brouard  8239:  - 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): \
                   8240:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8241:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8242:    fprintf(fichtm,"\
1.126     brouard  8243:  - (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): \
                   8244:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8245:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8246:    fprintf(fichtm,"\
1.288     brouard  8247:  - 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  8248:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8249:    fprintf(fichtm,"\
1.128     brouard  8250:  - 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  8251:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8252:    fprintf(fichtm,"\
1.288     brouard  8253:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8254:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8255: 
                   8256: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8257: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8258: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8259: /*     <br>",fileres,fileres,fileres,fileres); */
                   8260: /*  else  */
1.338     brouard  8261: /*    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  8262:    fflush(fichtm);
1.126     brouard  8263: 
1.225     brouard  8264:    m=pow(2,cptcoveff);
1.222     brouard  8265:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8266: 
1.317     brouard  8267:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8268: 
                   8269:   jj1=0;
                   8270: 
                   8271:    fprintf(fichtm," \n<ul>");
1.337     brouard  8272:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8273:      /* k1=nres; */
1.338     brouard  8274:      k1=TKresult[nres];
1.337     brouard  8275:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8276:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8277:      /*   continue; */
1.317     brouard  8278:      jj1++;
                   8279:      if (cptcovn > 0) {
                   8280:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8281:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8282:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8283:        }
                   8284:        fprintf(fichtm,"\">");
                   8285:        
                   8286:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8287:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8288:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8289:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8290:        }
                   8291:        if(invalidvarcomb[k1]){
                   8292:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8293:         continue;
                   8294:        }
                   8295:        fprintf(fichtm,"</a></li>");
                   8296:      } /* cptcovn >0 */
1.337     brouard  8297:    } /* End nres */
1.317     brouard  8298:    fprintf(fichtm," \n</ul>");
                   8299: 
1.222     brouard  8300:    jj1=0;
1.237     brouard  8301: 
1.241     brouard  8302:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8303:      /* k1=nres; */
1.338     brouard  8304:      k1=TKresult[nres];
                   8305:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8306:      /* for(k1=1; k1<=m;k1++){ */
                   8307:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8308:      /*   continue; */
1.222     brouard  8309:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8310:      jj1++;
1.126     brouard  8311:      if (cptcovn > 0) {
1.317     brouard  8312:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8313:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8314:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8315:        }
                   8316:        fprintf(fichtm,"\"</a>");
                   8317:        
1.126     brouard  8318:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8319:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8320:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8321:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8322:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8323:        }
1.237     brouard  8324: 
1.338     brouard  8325:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8326: 
1.222     brouard  8327:        if(invalidvarcomb[k1]){
                   8328:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8329:         continue;
                   8330:        }
1.337     brouard  8331:      } /* If cptcovn >0 */
1.126     brouard  8332:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8333:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8334: 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);
                   8335:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8336:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8337:      }
                   8338:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8339: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8340: true period expectancies (those weighted with period prevalences are also\
                   8341:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8342:  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);
                   8343:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8344:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8345:      /* } /\* end i1 *\/ */
1.241     brouard  8346:   }/* End nres */
1.222     brouard  8347:    fprintf(fichtm,"</ul>");
                   8348:    fflush(fichtm);
1.126     brouard  8349: }
                   8350: 
                   8351: /******************* Gnuplot file **************/
1.296     brouard  8352: 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  8353: 
                   8354:   char dirfileres[132],optfileres[132];
1.264     brouard  8355:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8356:   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  8357:   int lv=0, vlv=0, kl=0;
1.130     brouard  8358:   int ng=0;
1.201     brouard  8359:   int vpopbased;
1.223     brouard  8360:   int ioffset; /* variable offset for columns */
1.270     brouard  8361:   int iyearc=1; /* variable column for year of projection  */
                   8362:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8363:   int nres=0; /* Index of resultline */
1.266     brouard  8364:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8365: 
1.126     brouard  8366: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8367: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8368: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8369: /*   } */
                   8370: 
                   8371:   /*#ifdef windows */
                   8372:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8373:   /*#endif */
1.225     brouard  8374:   m=pow(2,cptcoveff);
1.126     brouard  8375: 
1.274     brouard  8376:   /* diagram of the model */
                   8377:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8378:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8379:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8380:   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);
                   8381: 
1.343     brouard  8382:   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  8383:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8384:   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);
                   8385:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8386:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8387:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8388:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8389: 
1.202     brouard  8390:   /* Contribution to likelihood */
                   8391:   /* Plot the probability implied in the likelihood */
1.223     brouard  8392:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8393:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8394:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8395:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8396: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8397:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8398: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8399:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8400:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8401:   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));
                   8402:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8403:   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));
                   8404:   for (i=1; i<= nlstate ; i ++) {
                   8405:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8406:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8407:     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);
                   8408:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8409:       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);
                   8410:     }
                   8411:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8412:   }
                   8413:   /* 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 */               
                   8414:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8415:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8416:   fprintf(ficgp,"\nset out;unset log\n");
                   8417:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8418: 
1.343     brouard  8419:   /* Plot the probability implied in the likelihood by covariate value */
                   8420:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8421:   /* if(debugILK==1){ */
                   8422:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8423:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8424:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8425:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
                   8426:     k=19+kf;/*offset because there are 19 columns in the ILK_ file */
1.343     brouard  8427:     for (i=1; i<= nlstate ; i ++) {
                   8428:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8429:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8430:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8431:        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);
                   8432:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8433:          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);
                   8434:        }
                   8435:       }else{
                   8436:        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);
                   8437:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8438:          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);
                   8439:        }
1.343     brouard  8440:       }
                   8441:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8442:     }
                   8443:   } /* End of each covariate dummy */
                   8444:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8445:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8446:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8447:      *  varying                   1     2                                 3       4        5
                   8448:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8449:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8450:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8451:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8452:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8453:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8454:      */
                   8455:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8456:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8457:     /* 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]); */
                   8458:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8459:       /* printf(" %d",ipos); */
                   8460:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8461:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8462:       kk++; /* Position of the ncovv column in ILK_ */
                   8463:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8464:       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)  */
                   8465:        for (i=1; i<= nlstate ; i ++) {
                   8466:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8467:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8468: 
1.348     brouard  8469:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8470:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8471:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8472:            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);
                   8473:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8474:              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);
                   8475:            }
                   8476:          }else{
                   8477:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8478:            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);
                   8479:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8480:              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);
                   8481:            }
                   8482:          }
                   8483:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8484:        }
                   8485:       }/* End if dummy varying */
                   8486:     }else{ /*Product */
                   8487:       /* printf("*"); */
                   8488:       /* fprintf(ficresilk,"*"); */
                   8489:     }
                   8490:     iposold=ipos;
                   8491:   } /* For each time varying covariate */
                   8492:   /* } /\* debugILK==1 *\/ */
                   8493:   /* 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 */               
                   8494:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8495:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8496:   fprintf(ficgp,"\nset out;unset log\n");
                   8497:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8498: 
                   8499: 
                   8500:   
1.126     brouard  8501:   strcpy(dirfileres,optionfilefiname);
                   8502:   strcpy(optfileres,"vpl");
1.223     brouard  8503:   /* 1eme*/
1.238     brouard  8504:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8505:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8506:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8507:        k1=TKresult[nres];
1.338     brouard  8508:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8509:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8510:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8511:        /*   continue; */
1.238     brouard  8512:        /* We are interested in selected combination by the resultline */
1.246     brouard  8513:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8514:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8515:        strcpy(gplotlabel,"(");
1.337     brouard  8516:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8517:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8518:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8519: 
                   8520:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8521:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8522:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8523:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8524:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8525:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8526:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8527:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8528:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8529:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8530:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8531:        /* } */
                   8532:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8533:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8534:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8535:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8536:        }
                   8537:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8538:        /* printf("\n#\n"); */
1.238     brouard  8539:        fprintf(ficgp,"\n#\n");
                   8540:        if(invalidvarcomb[k1]){
1.260     brouard  8541:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8542:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8543:          continue;
                   8544:        }
1.235     brouard  8545:       
1.241     brouard  8546:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8547:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8548:        /* 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  8549:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8550:        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);
                   8551:        /* 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); */
                   8552:       /* k1-1 error should be nres-1*/
1.238     brouard  8553:        for (i=1; i<= nlstate ; i ++) {
                   8554:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8555:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8556:        }
1.288     brouard  8557:        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  8558:        for (i=1; i<= nlstate ; i ++) {
                   8559:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8560:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8561:        } 
1.260     brouard  8562:        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  8563:        for (i=1; i<= nlstate ; i ++) {
                   8564:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8565:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8566:        }  
1.265     brouard  8567:        /* 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)); */
                   8568:        
                   8569:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8570:         if(cptcoveff ==0){
1.271     brouard  8571:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8572:        }else{
                   8573:          kl=0;
                   8574:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8575:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8576:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8577:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8578:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8579:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8580:            vlv= nbcode[Tvaraff[k]][lv];
                   8581:            kl++;
                   8582:            /* 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 *\/ */
                   8583:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8584:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8585:            /* ''  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*/
                   8586:            if(k==cptcoveff){
                   8587:              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], \
                   8588:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8589:            }else{
                   8590:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8591:              kl++;
                   8592:            }
                   8593:          } /* end covariate */
                   8594:        } /* end if no covariate */
                   8595: 
1.296     brouard  8596:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8597:          /* 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  8598:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8599:          if(cptcoveff ==0){
1.245     brouard  8600:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8601:          }else{
                   8602:            kl=0;
                   8603:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8604:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8605:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8606:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8607:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8608:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8609:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8610:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8611:              kl++;
1.238     brouard  8612:              /* 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 *\/ */
                   8613:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8614:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8615:              /* ''  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*/
                   8616:              if(k==cptcoveff){
1.245     brouard  8617:                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  8618:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8619:              }else{
1.332     brouard  8620:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8621:                kl++;
                   8622:              }
                   8623:            } /* end covariate */
                   8624:          } /* end if no covariate */
1.296     brouard  8625:          if(prevbcast == 1){
1.268     brouard  8626:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8627:            /* k1-1 error should be nres-1*/
                   8628:            for (i=1; i<= nlstate ; i ++) {
                   8629:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8630:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8631:            }
1.271     brouard  8632:            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  8633:            for (i=1; i<= nlstate ; i ++) {
                   8634:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8635:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8636:            } 
1.276     brouard  8637:            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  8638:            for (i=1; i<= nlstate ; i ++) {
                   8639:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8640:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8641:            } 
1.274     brouard  8642:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8643:          } /* end if backprojcast */
1.296     brouard  8644:        } /* end if prevbcast */
1.276     brouard  8645:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8646:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8647:       } /* nres */
1.337     brouard  8648:     /* } /\* k1 *\/ */
1.201     brouard  8649:   } /* cpt */
1.235     brouard  8650: 
                   8651:   
1.126     brouard  8652:   /*2 eme*/
1.337     brouard  8653:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8654:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8655:       k1=TKresult[nres];
1.338     brouard  8656:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8657:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8658:       /*       continue; */
1.238     brouard  8659:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8660:       strcpy(gplotlabel,"(");
1.337     brouard  8661:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8662:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8663:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8664:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8665:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8666:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8667:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8668:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8669:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8670:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8671:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8672:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8673:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8674:       /* } */
                   8675:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8676:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8677:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8678:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8679:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8680:       }
1.264     brouard  8681:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8682:       fprintf(ficgp,"\n#\n");
1.223     brouard  8683:       if(invalidvarcomb[k1]){
                   8684:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8685:        continue;
                   8686:       }
1.219     brouard  8687:                        
1.241     brouard  8688:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8689:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8690:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8691:        if(vpopbased==0){
1.238     brouard  8692:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8693:        }else
1.238     brouard  8694:          fprintf(ficgp,"\nreplot ");
                   8695:        for (i=1; i<= nlstate+1 ; i ++) {
                   8696:          k=2*i;
1.261     brouard  8697:          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  8698:          for (j=1; j<= nlstate+1 ; j ++) {
                   8699:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8700:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8701:          }   
                   8702:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8703:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8704:          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  8705:          for (j=1; j<= nlstate+1 ; j ++) {
                   8706:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8707:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8708:          }   
                   8709:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8710:          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  8711:          for (j=1; j<= nlstate+1 ; j ++) {
                   8712:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8713:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8714:          }   
                   8715:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8716:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8717:        } /* state */
                   8718:       } /* vpopbased */
1.264     brouard  8719:       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  8720:     } /* end nres */
1.337     brouard  8721:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8722:        
                   8723:        
                   8724:   /*3eme*/
1.337     brouard  8725:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8726:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8727:       k1=TKresult[nres];
1.338     brouard  8728:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8729:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8730:       /*       continue; */
1.238     brouard  8731: 
1.332     brouard  8732:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8733:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8734:        strcpy(gplotlabel,"(");
1.337     brouard  8735:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8736:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8737:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8738:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8739:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8740:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8741:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8742:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8743:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8744:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8745:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8746:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8747:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8748:        /* } */
                   8749:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8750:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8751:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8752:        }
1.264     brouard  8753:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8754:        fprintf(ficgp,"\n#\n");
                   8755:        if(invalidvarcomb[k1]){
                   8756:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8757:          continue;
                   8758:        }
                   8759:                        
                   8760:        /*       k=2+nlstate*(2*cpt-2); */
                   8761:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8762:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8763:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8764:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8765: 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  8766:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8767:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8768:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8769:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8770:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8771:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8772:                                
1.238     brouard  8773:        */
                   8774:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8775:          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  8776:          /*    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  8777:                                
1.238     brouard  8778:        } 
1.261     brouard  8779:        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  8780:       }
1.264     brouard  8781:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8782:     } /* end nres */
1.337     brouard  8783:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8784:   
1.223     brouard  8785:   /* 4eme */
1.201     brouard  8786:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8787:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8788:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8789:       k1=TKresult[nres];
1.338     brouard  8790:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8791:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8792:       /*       continue; */
1.238     brouard  8793:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8794:        strcpy(gplotlabel,"(");
1.337     brouard  8795:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8796:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8797:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8798:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8799:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8800:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8801:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8802:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8803:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8804:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8805:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8806:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8807:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8808:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8809:        /* } */
                   8810:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8811:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8812:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8813:        }       
1.264     brouard  8814:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8815:        fprintf(ficgp,"\n#\n");
                   8816:        if(invalidvarcomb[k1]){
                   8817:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8818:          continue;
1.223     brouard  8819:        }
1.238     brouard  8820:       
1.241     brouard  8821:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8822:        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  8823:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8824: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8825:        k=3;
                   8826:        for (i=1; i<= nlstate ; i ++){
                   8827:          if(i==1){
                   8828:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8829:          }else{
                   8830:            fprintf(ficgp,", '' ");
                   8831:          }
                   8832:          l=(nlstate+ndeath)*(i-1)+1;
                   8833:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8834:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8835:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8836:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8837:        } /* nlstate */
1.264     brouard  8838:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8839:       } /* end cpt state*/ 
                   8840:     } /* end nres */
1.337     brouard  8841:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8842: 
1.220     brouard  8843: /* 5eme */
1.201     brouard  8844:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8845:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8846:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8847:       k1=TKresult[nres];
1.338     brouard  8848:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8849:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8850:       /*       continue; */
1.238     brouard  8851:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8852:        strcpy(gplotlabel,"(");
1.238     brouard  8853:        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  8854:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8855:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8856:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8857:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8858:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8859:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8860:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8861:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8862:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8863:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8864:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8865:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8866:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8867:        /* } */
                   8868:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8869:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8870:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8871:        }       
1.264     brouard  8872:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8873:        fprintf(ficgp,"\n#\n");
                   8874:        if(invalidvarcomb[k1]){
                   8875:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8876:          continue;
                   8877:        }
1.227     brouard  8878:       
1.241     brouard  8879:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8880:        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  8881:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8882: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8883:        k=3;
                   8884:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8885:          if(j==1)
                   8886:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8887:          else
                   8888:            fprintf(ficgp,", '' ");
                   8889:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8890:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8891:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8892:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8893:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8894:        } /* nlstate */
                   8895:        fprintf(ficgp,", '' ");
                   8896:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8897:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8898:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8899:          if(j < nlstate)
                   8900:            fprintf(ficgp,"$%d +",k+l);
                   8901:          else
                   8902:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8903:        }
1.264     brouard  8904:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8905:       } /* end cpt state*/ 
1.337     brouard  8906:     /* } /\* end covariate *\/   */
1.238     brouard  8907:   } /* end nres */
1.227     brouard  8908:   
1.220     brouard  8909: /* 6eme */
1.202     brouard  8910:   /* CV preval stable (period) for each covariate */
1.337     brouard  8911:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8912:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8913:      k1=TKresult[nres];
1.338     brouard  8914:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8915:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8916:      /*  continue; */
1.255     brouard  8917:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8918:       strcpy(gplotlabel,"(");      
1.288     brouard  8919:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8920:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8921:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8922:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8923:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8924:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8925:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8926:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8927:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8928:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8929:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8930:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8931:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8932:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8933:       /* } */
                   8934:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8935:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8936:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8937:       }        
1.264     brouard  8938:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8939:       fprintf(ficgp,"\n#\n");
1.223     brouard  8940:       if(invalidvarcomb[k1]){
1.227     brouard  8941:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8942:        continue;
1.223     brouard  8943:       }
1.227     brouard  8944:       
1.241     brouard  8945:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8946:       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  8947:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8948: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8949:       k=3; /* Offset */
1.255     brouard  8950:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8951:        if(i==1)
                   8952:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8953:        else
                   8954:          fprintf(ficgp,", '' ");
1.255     brouard  8955:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8956:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8957:        for (j=2; j<= nlstate ; j ++)
                   8958:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8959:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8960:       } /* nlstate */
1.264     brouard  8961:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8962:     } /* end cpt state*/ 
                   8963:   } /* end covariate */  
1.227     brouard  8964:   
                   8965:   
1.220     brouard  8966: /* 7eme */
1.296     brouard  8967:   if(prevbcast == 1){
1.288     brouard  8968:     /* CV backward prevalence  for each covariate */
1.337     brouard  8969:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8970:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8971:       k1=TKresult[nres];
1.338     brouard  8972:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8973:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8974:       /*       continue; */
1.268     brouard  8975:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8976:        strcpy(gplotlabel,"(");      
1.288     brouard  8977:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8978:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8979:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8980:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8981:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8982:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8983:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8984:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8985:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8986:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8987:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8988:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8989:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8990:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8991:        /* } */
                   8992:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8993:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8994:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8995:        }       
1.264     brouard  8996:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8997:        fprintf(ficgp,"\n#\n");
                   8998:        if(invalidvarcomb[k1]){
                   8999:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9000:          continue;
                   9001:        }
                   9002:        
1.241     brouard  9003:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9004:        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  9005:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9006: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9007:        k=3; /* Offset */
1.268     brouard  9008:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9009:          if(i==1)
                   9010:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9011:          else
                   9012:            fprintf(ficgp,", '' ");
                   9013:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9014:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9015:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9016:          /* 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  9017:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9018:          /* for (j=2; j<= nlstate ; j ++) */
                   9019:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9020:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9021:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9022:        } /* nlstate */
1.264     brouard  9023:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9024:       } /* end cpt state*/ 
                   9025:     } /* end covariate */  
1.296     brouard  9026:   } /* End if prevbcast */
1.218     brouard  9027:   
1.223     brouard  9028:   /* 8eme */
1.218     brouard  9029:   if(prevfcast==1){
1.288     brouard  9030:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9031:     
1.337     brouard  9032:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9033:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9034:       k1=TKresult[nres];
1.338     brouard  9035:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9036:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9037:       /*       continue; */
1.211     brouard  9038:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9039:        strcpy(gplotlabel,"(");      
1.288     brouard  9040:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9041:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9042:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9043:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9044:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9045:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9046:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9047:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9048:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9049:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9050:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9051:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9052:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9053:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9054:        /* } */
                   9055:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9056:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9057:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9058:        }       
1.264     brouard  9059:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9060:        fprintf(ficgp,"\n#\n");
                   9061:        if(invalidvarcomb[k1]){
                   9062:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9063:          continue;
                   9064:        }
                   9065:        
                   9066:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9067:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9068:        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  9069:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9070: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9071: 
                   9072:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9073:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9074:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9075:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9076:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9077:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9078:          /*# 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 */   
1.266     brouard  9080:          if(i==istart){
1.227     brouard  9081:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9082:          }else{
                   9083:            fprintf(ficgp,",\\\n '' ");
                   9084:          }
                   9085:          if(cptcoveff ==0){ /* No covariate */
                   9086:            ioffset=2; /* Age is in 2 */
                   9087:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9088:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9089:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9090:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9091:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9092:            if(i==nlstate+1){
1.270     brouard  9093:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9094:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9095:              fprintf(ficgp,",\\\n '' ");
                   9096:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9097:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9098:                     offyear,                           \
1.268     brouard  9099:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9100:            }else
1.227     brouard  9101:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9102:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9103:          }else{ /* more than 2 covariates */
1.270     brouard  9104:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9105:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9106:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9107:            iyearc=ioffset-1;
                   9108:            iagec=ioffset;
1.227     brouard  9109:            fprintf(ficgp," u %d:(",ioffset); 
                   9110:            kl=0;
                   9111:            strcpy(gplotcondition,"(");
1.351   ! brouard  9112:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9113:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351   ! brouard  9114:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          9115:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          9116:              lv=Tvresult[nres][k];
        !          9117:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9118:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9119:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9120:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9121:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351   ! brouard  9122:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9123:              kl++;
1.351   ! brouard  9124:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
        !          9125:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9126:              kl++;
1.351   ! brouard  9127:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9128:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9129:            }
                   9130:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9131:            /* 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 *\/ */
                   9132:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9133:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9134:            /* ''  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*/
                   9135:            if(i==nlstate+1){
1.270     brouard  9136:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9137:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9138:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9139:              fprintf(ficgp," u %d:(",iagec); 
                   9140:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9141:                      iyearc, iagec, offyear,                           \
                   9142:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9143: /*  '' 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  9144:            }else{
                   9145:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9146:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9147:            }
                   9148:          } /* end if covariate */
                   9149:        } /* nlstate */
1.264     brouard  9150:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9151:       } /* end cpt state*/
                   9152:     } /* end covariate */
                   9153:   } /* End if prevfcast */
1.227     brouard  9154:   
1.296     brouard  9155:   if(prevbcast==1){
1.268     brouard  9156:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9157:     
1.337     brouard  9158:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9159:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9160:      k1=TKresult[nres];
1.338     brouard  9161:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9162:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9163:        /*      continue; */
1.268     brouard  9164:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9165:        strcpy(gplotlabel,"(");      
                   9166:        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  9167:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9168:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9169:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9170:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9171:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9172:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9173:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9174:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9175:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9176:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9177:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9178:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9179:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9180:        /* } */
                   9181:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9182:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9183:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9184:        }       
                   9185:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9186:        fprintf(ficgp,"\n#\n");
                   9187:        if(invalidvarcomb[k1]){
                   9188:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9189:          continue;
                   9190:        }
                   9191:        
                   9192:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9193:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9194:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9195:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9196: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9197: 
                   9198:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9199:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9200:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9201:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9202:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9203:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9204:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9205:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9206:          if(i==istart){
                   9207:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9208:          }else{
                   9209:            fprintf(ficgp,",\\\n '' ");
                   9210:          }
1.351   ! brouard  9211:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
        !          9212:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9213:            ioffset=2; /* Age is in 2 */
                   9214:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9215:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9216:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9217:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9218:            fprintf(ficgp," u %d:(", ioffset); 
                   9219:            if(i==nlstate+1){
1.270     brouard  9220:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9221:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9222:              fprintf(ficgp,",\\\n '' ");
                   9223:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9224:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9225:                     offbyear,                          \
                   9226:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9227:            }else
                   9228:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9229:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9230:          }else{ /* more than 2 covariates */
1.270     brouard  9231:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9232:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9233:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9234:            iyearc=ioffset-1;
                   9235:            iagec=ioffset;
1.268     brouard  9236:            fprintf(ficgp," u %d:(",ioffset); 
                   9237:            kl=0;
                   9238:            strcpy(gplotcondition,"(");
1.337     brouard  9239:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9240:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9241:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9242:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9243:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9244:                lv=Tvresult[nres][k];
                   9245:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9246:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9247:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9248:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9249:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9250:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9251:                kl++;
                   9252:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9253:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9254:                kl++;
1.338     brouard  9255:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9256:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9257:              }
1.268     brouard  9258:            }
                   9259:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9260:            /* 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 *\/ */
                   9261:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9262:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9263:            /* ''  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*/
                   9264:            if(i==nlstate+1){
1.270     brouard  9265:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9266:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9267:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9268:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9269:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9270:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9271:                      iyearc,iagec,offbyear,                            \
                   9272:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9273: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9274:            }else{
                   9275:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9276:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9277:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9278:            }
                   9279:          } /* end if covariate */
                   9280:        } /* nlstate */
                   9281:        fprintf(ficgp,"\nset out; unset label;\n");
                   9282:       } /* end cpt state*/
                   9283:     } /* end covariate */
1.296     brouard  9284:   } /* End if prevbcast */
1.268     brouard  9285:   
1.227     brouard  9286:   
1.238     brouard  9287:   /* 9eme writing MLE parameters */
                   9288:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9289:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9290:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9291:     for(k=1; k <=(nlstate+ndeath); k++){
                   9292:       if (k != i) {
1.227     brouard  9293:        fprintf(ficgp,"#   current state %d\n",k);
                   9294:        for(j=1; j <=ncovmodel; j++){
                   9295:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9296:          jk++; 
                   9297:        }
                   9298:        fprintf(ficgp,"\n");
1.126     brouard  9299:       }
                   9300:     }
1.223     brouard  9301:   }
1.187     brouard  9302:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9303:   
1.145     brouard  9304:   /*goto avoid;*/
1.238     brouard  9305:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9306:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9307:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9308:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9309:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9310:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9311:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9312:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9313:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9314:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9315:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9316:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9317:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9318:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9319:   fprintf(ficgp,"#\n");
1.223     brouard  9320:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9321:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9322:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9323:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351   ! brouard  9324:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
        !          9325:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9326:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9327:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9328:      /* k1=nres; */
1.338     brouard  9329:       k1=TKresult[nres];
                   9330:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9331:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9332:       strcpy(gplotlabel,"(");
1.276     brouard  9333:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9334:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9335:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9336:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9337:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9338:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9339:       }
                   9340:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9341:       /*       continue; */
                   9342:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9343:       /* strcpy(gplotlabel,"("); */
                   9344:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9345:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9346:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9347:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9348:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9349:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9350:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9351:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9352:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9353:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9354:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9355:       /* } */
                   9356:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9357:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9358:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9359:       /* }      */
1.264     brouard  9360:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9361:       fprintf(ficgp,"\n#\n");
1.264     brouard  9362:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9363:       fprintf(ficgp,"\nset key outside ");
                   9364:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9365:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9366:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9367:       if (ng==1){
                   9368:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9369:        fprintf(ficgp,"\nunset log y");
                   9370:       }else if (ng==2){
                   9371:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9372:        fprintf(ficgp,"\nset log y");
                   9373:       }else if (ng==3){
                   9374:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9375:        fprintf(ficgp,"\nset log y");
                   9376:       }else
                   9377:        fprintf(ficgp,"\nunset title ");
                   9378:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9379:       i=1;
                   9380:       for(k2=1; k2<=nlstate; k2++) {
                   9381:        k3=i;
                   9382:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9383:          if (k != k2){
                   9384:            switch( ng) {
                   9385:            case 1:
                   9386:              if(nagesqr==0)
                   9387:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9388:              else /* nagesqr =1 */
                   9389:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9390:              break;
                   9391:            case 2: /* ng=2 */
                   9392:              if(nagesqr==0)
                   9393:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9394:              else /* nagesqr =1 */
                   9395:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9396:              break;
                   9397:            case 3:
                   9398:              if(nagesqr==0)
                   9399:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9400:              else /* nagesqr =1 */
                   9401:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9402:              break;
                   9403:            }
                   9404:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9405:            ijp=1; /* product no age */
                   9406:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9407:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9408:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9409:              switch(Typevar[j]){
                   9410:              case 1:
                   9411:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9412:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9413:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9414:                      if(DummyV[j]==0){/* Bug valgrind */
                   9415:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9416:                      }else{ /* quantitative */
                   9417:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9418:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9419:                      }
                   9420:                      ij++;
1.268     brouard  9421:                    }
1.237     brouard  9422:                  }
1.329     brouard  9423:                }
                   9424:                break;
                   9425:              case 2:
                   9426:                if(cptcovprod >0){
                   9427:                  if(j==Tprod[ijp]) { /* */ 
                   9428:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9429:                    if(ijp <=cptcovprod) { /* Product */
                   9430:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9431:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9432:                          /* 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)]); */
                   9433:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9434:                        }else{ /* Vn is dummy and Vm is quanti */
                   9435:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9436:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9437:                        }
                   9438:                      }else{ /* Vn*Vm Vn is quanti */
                   9439:                        if(DummyV[Tvard[ijp][2]]==0){
                   9440:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9441:                        }else{ /* Both quanti */
                   9442:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9443:                        }
1.268     brouard  9444:                      }
1.329     brouard  9445:                      ijp++;
1.237     brouard  9446:                    }
1.329     brouard  9447:                  } /* end Tprod */
                   9448:                }
                   9449:                break;
1.349     brouard  9450:              case 3:
                   9451:                if(cptcovdageprod >0){
                   9452:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9453:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9454:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9455:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9456:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9457:                          /* 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)]); */
                   9458:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9459:                        }else{ /* Vn is dummy and Vm is quanti */
                   9460:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  9461:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9462:                        }
1.350     brouard  9463:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9464:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9465:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  9466:                        }else{ /* Both quanti */
1.350     brouard  9467:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9468:                        }
                   9469:                      }
                   9470:                      ijp++;
                   9471:                    }
                   9472:                    /* } */ /* end Tprod */
                   9473:                }
                   9474:                break;
1.329     brouard  9475:              case 0:
                   9476:                /* simple covariate */
1.264     brouard  9477:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9478:                if(Dummy[j]==0){
                   9479:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9480:                }else{ /* quantitative */
                   9481:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9482:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9483:                }
1.329     brouard  9484:               /* end simple */
                   9485:                break;
                   9486:              default:
                   9487:                break;
                   9488:              } /* end switch */
1.237     brouard  9489:            } /* end j */
1.329     brouard  9490:          }else{ /* k=k2 */
                   9491:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9492:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9493:            }else
                   9494:              i=i-ncovmodel;
1.223     brouard  9495:          }
1.227     brouard  9496:          
1.223     brouard  9497:          if(ng != 1){
                   9498:            fprintf(ficgp,")/(1");
1.227     brouard  9499:            
1.264     brouard  9500:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9501:              if(nagesqr==0)
1.264     brouard  9502:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9503:              else /* nagesqr =1 */
1.264     brouard  9504:                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  9505:               
1.223     brouard  9506:              ij=1;
1.329     brouard  9507:              ijp=1;
                   9508:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9509:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9510:                switch(Typevar[j]){
                   9511:                case 1:
                   9512:                  if(cptcovage >0){ 
                   9513:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9514:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9515:                        if(DummyV[j]==0){/* Bug valgrind */
                   9516:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9517:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9518:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9519:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9520:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9521:                        }else{ /* quantitative */
                   9522:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9523:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9524:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9525:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9526:                        }
                   9527:                        ij++;
                   9528:                      }
                   9529:                    }
                   9530:                  }
                   9531:                  break;
                   9532:                case 2:
                   9533:                  if(cptcovprod >0){
                   9534:                    if(j==Tprod[ijp]) { /* */ 
                   9535:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9536:                      if(ijp <=cptcovprod) { /* Product */
                   9537:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9538:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9539:                            /* 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)]); */
                   9540:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9541:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9542:                          }else{ /* Vn is dummy and Vm is quanti */
                   9543:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9544:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9545:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9546:                          }
                   9547:                        }else{ /* Vn*Vm Vn is quanti */
                   9548:                          if(DummyV[Tvard[ijp][2]]==0){
                   9549:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9550:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9551:                          }else{ /* Both quanti */
                   9552:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9553:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9554:                          } 
                   9555:                        }
                   9556:                        ijp++;
                   9557:                      }
                   9558:                    } /* end Tprod */
                   9559:                  } /* end if */
                   9560:                  break;
1.349     brouard  9561:                case 3:
                   9562:                  if(cptcovdageprod >0){
                   9563:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9564:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9565:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9566:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9567:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9568:                            /* 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)]); */
1.350     brouard  9569:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9570:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9571:                          }else{ /* Vn is dummy and Vm is quanti */
                   9572:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  9573:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9574:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9575:                          }
                   9576:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9577:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9578:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  9579:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9580:                          }else{ /* Both quanti */
1.350     brouard  9581:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  9582:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9583:                          } 
                   9584:                        }
                   9585:                        ijp++;
                   9586:                      }
                   9587:                    /* } /\* end Tprod *\/ */
                   9588:                  } /* end if */
                   9589:                  break;
1.329     brouard  9590:                case 0: 
                   9591:                  /* simple covariate */
                   9592:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9593:                  if(Dummy[j]==0){
                   9594:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9595:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9596:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9597:                  }else{ /* quantitative */
                   9598:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9599:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9600:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9601:                  }
                   9602:                  /* end simple */
                   9603:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9604:                  break;
                   9605:                default:
                   9606:                  break;
                   9607:                } /* end switch */
1.223     brouard  9608:              }
                   9609:              fprintf(ficgp,")");
                   9610:            }
                   9611:            fprintf(ficgp,")");
                   9612:            if(ng ==2)
1.276     brouard  9613:              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  9614:            else /* ng= 3 */
1.276     brouard  9615:              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  9616:           }else{ /* end ng <> 1 */
1.223     brouard  9617:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9618:              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  9619:          }
                   9620:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9621:            fprintf(ficgp,",");
                   9622:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9623:            fprintf(ficgp,",");
                   9624:          i=i+ncovmodel;
                   9625:        } /* end k */
                   9626:       } /* end k2 */
1.276     brouard  9627:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9628:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9629:     } /* end resultline */
1.223     brouard  9630:   } /* end ng */
                   9631:   /* avoid: */
                   9632:   fflush(ficgp); 
1.126     brouard  9633: }  /* end gnuplot */
                   9634: 
                   9635: 
                   9636: /*************** Moving average **************/
1.219     brouard  9637: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9638:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9639:    
1.222     brouard  9640:    int i, cpt, cptcod;
                   9641:    int modcovmax =1;
                   9642:    int mobilavrange, mob;
                   9643:    int iage=0;
1.288     brouard  9644:    int firstA1=0, firstA2=0;
1.222     brouard  9645: 
1.266     brouard  9646:    double sum=0., sumr=0.;
1.222     brouard  9647:    double age;
1.266     brouard  9648:    double *sumnewp, *sumnewm, *sumnewmr;
                   9649:    double *agemingood, *agemaxgood; 
                   9650:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9651:   
                   9652:   
1.278     brouard  9653:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9654:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9655: 
                   9656:    sumnewp = vector(1,ncovcombmax);
                   9657:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9658:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9659:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9660:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9661:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9662:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9663: 
                   9664:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9665:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9666:      sumnewp[cptcod]=0.;
1.266     brouard  9667:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9668:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9669:    }
                   9670:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9671:   
1.266     brouard  9672:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9673:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9674:      else mobilavrange=mobilav;
                   9675:      for (age=bage; age<=fage; age++)
                   9676:        for (i=1; i<=nlstate;i++)
                   9677:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9678:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9679:      /* We keep the original values on the extreme ages bage, fage and for 
                   9680:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9681:        we use a 5 terms etc. until the borders are no more concerned. 
                   9682:      */ 
                   9683:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9684:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9685:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9686:           sumnewm[cptcod]=0.;
                   9687:           for (i=1; i<=nlstate;i++){
1.222     brouard  9688:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9689:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9690:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9691:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9692:             }
                   9693:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9694:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9695:           } /* end i */
                   9696:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9697:         } /* end cptcod */
1.222     brouard  9698:        }/* end age */
                   9699:      }/* end mob */
1.266     brouard  9700:    }else{
                   9701:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9702:      return -1;
1.266     brouard  9703:    }
                   9704: 
                   9705:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9706:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9707:      if(invalidvarcomb[cptcod]){
                   9708:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9709:        continue;
                   9710:      }
1.219     brouard  9711: 
1.266     brouard  9712:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9713:        sumnewm[cptcod]=0.;
                   9714:        sumnewmr[cptcod]=0.;
                   9715:        for (i=1; i<=nlstate;i++){
                   9716:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9717:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9718:        }
                   9719:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9720:         agemingoodr[cptcod]=age;
                   9721:        }
                   9722:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9723:           agemingood[cptcod]=age;
                   9724:        }
                   9725:      } /* age */
                   9726:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9727:        sumnewm[cptcod]=0.;
1.266     brouard  9728:        sumnewmr[cptcod]=0.;
1.222     brouard  9729:        for (i=1; i<=nlstate;i++){
                   9730:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9731:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9732:        }
                   9733:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9734:         agemaxgoodr[cptcod]=age;
1.222     brouard  9735:        }
                   9736:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9737:         agemaxgood[cptcod]=age;
                   9738:        }
                   9739:      } /* age */
                   9740:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9741:      /* but they will change */
1.288     brouard  9742:      firstA1=0;firstA2=0;
1.266     brouard  9743:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9744:        sumnewm[cptcod]=0.;
                   9745:        sumnewmr[cptcod]=0.;
                   9746:        for (i=1; i<=nlstate;i++){
                   9747:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9748:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9749:        }
                   9750:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9751:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9752:           agemaxgoodr[cptcod]=age;  /* age min */
                   9753:           for (i=1; i<=nlstate;i++)
                   9754:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9755:         }else{ /* bad we change the value with the values of good ages */
                   9756:           for (i=1; i<=nlstate;i++){
                   9757:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9758:           } /* i */
                   9759:         } /* end bad */
                   9760:        }else{
                   9761:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9762:           agemaxgood[cptcod]=age;
                   9763:         }else{ /* bad we change the value with the values of good ages */
                   9764:           for (i=1; i<=nlstate;i++){
                   9765:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9766:           } /* i */
                   9767:         } /* end bad */
                   9768:        }/* end else */
                   9769:        sum=0.;sumr=0.;
                   9770:        for (i=1; i<=nlstate;i++){
                   9771:         sum+=mobaverage[(int)age][i][cptcod];
                   9772:         sumr+=probs[(int)age][i][cptcod];
                   9773:        }
                   9774:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9775:         if(!firstA1){
                   9776:           firstA1=1;
                   9777:           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);
                   9778:         }
                   9779:         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  9780:        } /* end bad */
                   9781:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9782:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9783:         if(!firstA2){
                   9784:           firstA2=1;
                   9785:           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);
                   9786:         }
                   9787:         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  9788:        } /* end bad */
                   9789:      }/* age */
1.266     brouard  9790: 
                   9791:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9792:        sumnewm[cptcod]=0.;
1.266     brouard  9793:        sumnewmr[cptcod]=0.;
1.222     brouard  9794:        for (i=1; i<=nlstate;i++){
                   9795:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9796:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9797:        } 
                   9798:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9799:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9800:           agemingoodr[cptcod]=age;
                   9801:           for (i=1; i<=nlstate;i++)
                   9802:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9803:         }else{ /* bad we change the value with the values of good ages */
                   9804:           for (i=1; i<=nlstate;i++){
                   9805:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9806:           } /* i */
                   9807:         } /* end bad */
                   9808:        }else{
                   9809:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9810:           agemingood[cptcod]=age;
                   9811:         }else{ /* bad */
                   9812:           for (i=1; i<=nlstate;i++){
                   9813:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9814:           } /* i */
                   9815:         } /* end bad */
                   9816:        }/* end else */
                   9817:        sum=0.;sumr=0.;
                   9818:        for (i=1; i<=nlstate;i++){
                   9819:         sum+=mobaverage[(int)age][i][cptcod];
                   9820:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9821:        }
1.266     brouard  9822:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9823:         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  9824:        } /* end bad */
                   9825:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9826:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9827:         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  9828:        } /* end bad */
                   9829:      }/* age */
1.266     brouard  9830: 
1.222     brouard  9831:                
                   9832:      for (age=bage; age<=fage; age++){
1.235     brouard  9833:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9834:        sumnewp[cptcod]=0.;
                   9835:        sumnewm[cptcod]=0.;
                   9836:        for (i=1; i<=nlstate;i++){
                   9837:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9838:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9839:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9840:        }
                   9841:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9842:      }
                   9843:      /* printf("\n"); */
                   9844:      /* } */
1.266     brouard  9845: 
1.222     brouard  9846:      /* brutal averaging */
1.266     brouard  9847:      /* for (i=1; i<=nlstate;i++){ */
                   9848:      /*   for (age=1; age<=bage; age++){ */
                   9849:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9850:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9851:      /*   }     */
                   9852:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9853:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9854:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9855:      /*   } */
                   9856:      /* } /\* end i status *\/ */
                   9857:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9858:      /*   for (age=1; age<=AGESUP; age++){ */
                   9859:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9860:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9861:      /*   } */
                   9862:      /* } */
1.222     brouard  9863:    }/* end cptcod */
1.266     brouard  9864:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9865:    free_vector(agemaxgood,1, ncovcombmax);
                   9866:    free_vector(agemingood,1, ncovcombmax);
                   9867:    free_vector(agemingoodr,1, ncovcombmax);
                   9868:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9869:    free_vector(sumnewm,1, ncovcombmax);
                   9870:    free_vector(sumnewp,1, ncovcombmax);
                   9871:    return 0;
                   9872:  }/* End movingaverage */
1.218     brouard  9873:  
1.126     brouard  9874: 
1.296     brouard  9875:  
1.126     brouard  9876: /************** Forecasting ******************/
1.296     brouard  9877: /* 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)*/
                   9878: 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){
                   9879:   /* dateintemean, mean date of interviews
                   9880:      dateprojd, year, month, day of starting projection 
                   9881:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9882:      agemin, agemax range of age
                   9883:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9884:   */
1.296     brouard  9885:   /* double anprojd, mprojd, jprojd; */
                   9886:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9887:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9888:   double agec; /* generic age */
1.296     brouard  9889:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9890:   double *popeffectif,*popcount;
                   9891:   double ***p3mat;
1.218     brouard  9892:   /* double ***mobaverage; */
1.126     brouard  9893:   char fileresf[FILENAMELENGTH];
                   9894: 
                   9895:   agelim=AGESUP;
1.211     brouard  9896:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9897:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9898:      We still use firstpass and lastpass as another selection.
                   9899:   */
1.214     brouard  9900:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9901:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9902:  
1.201     brouard  9903:   strcpy(fileresf,"F_"); 
                   9904:   strcat(fileresf,fileresu);
1.126     brouard  9905:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9906:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9907:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9908:   }
1.235     brouard  9909:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9910:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9911: 
1.225     brouard  9912:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9913: 
                   9914: 
                   9915:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9916:   if (stepm<=12) stepsize=1;
                   9917:   if(estepm < stepm){
                   9918:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9919:   }
1.270     brouard  9920:   else{
                   9921:     hstepm=estepm;   
                   9922:   }
                   9923:   if(estepm > stepm){ /* Yes every two year */
                   9924:     stepsize=2;
                   9925:   }
1.296     brouard  9926:   hstepm=hstepm/stepm;
1.126     brouard  9927: 
1.296     brouard  9928:   
                   9929:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9930:   /*                              fractional in yp1 *\/ */
                   9931:   /* aintmean=yp; */
                   9932:   /* yp2=modf((yp1*12),&yp); */
                   9933:   /* mintmean=yp; */
                   9934:   /* yp1=modf((yp2*30.5),&yp); */
                   9935:   /* jintmean=yp; */
                   9936:   /* if(jintmean==0) jintmean=1; */
                   9937:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9938: 
1.296     brouard  9939: 
                   9940:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9941:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9942:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351   ! brouard  9943:   /* i1=pow(2,cptcoveff); */
        !          9944:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9945:   
1.296     brouard  9946:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9947:   
                   9948:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9949:   
1.126     brouard  9950: /*           if (h==(int)(YEARM*yearp)){ */
1.351   ! brouard  9951:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          9952:     k=TKresult[nres];
        !          9953:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
        !          9954:     /*  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) *\/ */
        !          9955:     /* if(i1 != 1 && TKresult[nres]!= k) */
        !          9956:     /*   continue; */
        !          9957:     /* if(invalidvarcomb[k]){ */
        !          9958:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
        !          9959:     /*   continue; */
        !          9960:     /* } */
1.227     brouard  9961:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351   ! brouard  9962:     for(j=1;j<=cptcovs;j++){
        !          9963:       /* for(j=1;j<=cptcoveff;j++) { */
        !          9964:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
        !          9965:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          9966:     /* } */
        !          9967:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          9968:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          9969:     /* } */
        !          9970:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  9971:     }
1.351   ! brouard  9972:  
1.227     brouard  9973:     fprintf(ficresf," yearproj age");
                   9974:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9975:       for(i=1; i<=nlstate;i++)               
                   9976:        fprintf(ficresf," p%d%d",i,j);
                   9977:       fprintf(ficresf," wp.%d",j);
                   9978:     }
1.296     brouard  9979:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9980:       fprintf(ficresf,"\n");
1.296     brouard  9981:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9982:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9983:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9984:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9985:        nhstepm = nhstepm/hstepm; 
                   9986:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9987:        oldm=oldms;savm=savms;
1.268     brouard  9988:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9989:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9990:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9991:        for (h=0; h<=nhstepm; h++){
                   9992:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9993:            break;
                   9994:          }
                   9995:        }
                   9996:        fprintf(ficresf,"\n");
1.351   ! brouard  9997:        /* for(j=1;j<=cptcoveff;j++)  */
        !          9998:        for(j=1;j<=cptcovs;j++) 
        !          9999:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10000:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351   ! brouard  10001:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10002:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10003:        
                   10004:        for(j=1; j<=nlstate+ndeath;j++) {
                   10005:          ppij=0.;
                   10006:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10007:            if (mobilav>=1)
                   10008:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10009:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10010:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10011:            }
1.268     brouard  10012:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10013:          } /* end i */
                   10014:          fprintf(ficresf," %.3f", ppij);
                   10015:        }/* end j */
1.227     brouard  10016:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10017:       } /* end agec */
1.266     brouard  10018:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10019:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10020:     } /* end yearp */
                   10021:   } /* end  k */
1.219     brouard  10022:        
1.126     brouard  10023:   fclose(ficresf);
1.215     brouard  10024:   printf("End of Computing forecasting \n");
                   10025:   fprintf(ficlog,"End of Computing forecasting\n");
                   10026: 
1.126     brouard  10027: }
                   10028: 
1.269     brouard  10029: /************** Back Forecasting ******************/
1.296     brouard  10030:  /* 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){ */
                   10031:  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){
                   10032:   /* back1, year, month, day of starting backprojection
1.267     brouard  10033:      agemin, agemax range of age
                   10034:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10035:      anback2 year of end of backprojection (same day and month as back1).
                   10036:      prevacurrent and prev are prevalences.
1.267     brouard  10037:   */
                   10038:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10039:   double agec; /* generic age */
1.302     brouard  10040:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10041:   double *popeffectif,*popcount;
                   10042:   double ***p3mat;
                   10043:   /* double ***mobaverage; */
                   10044:   char fileresfb[FILENAMELENGTH];
                   10045:  
1.268     brouard  10046:   agelim=AGEINF;
1.267     brouard  10047:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10048:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10049:      We still use firstpass and lastpass as another selection.
                   10050:   */
                   10051:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10052:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10053: 
                   10054:   /*Do we need to compute prevalence again?*/
                   10055: 
                   10056:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10057:   
                   10058:   strcpy(fileresfb,"FB_");
                   10059:   strcat(fileresfb,fileresu);
                   10060:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10061:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10062:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10063:   }
                   10064:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10065:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10066:   
                   10067:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10068:   
                   10069:    
                   10070:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10071:   if (stepm<=12) stepsize=1;
                   10072:   if(estepm < stepm){
                   10073:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10074:   }
1.270     brouard  10075:   else{
                   10076:     hstepm=estepm;   
                   10077:   }
                   10078:   if(estepm >= stepm){ /* Yes every two year */
                   10079:     stepsize=2;
                   10080:   }
1.267     brouard  10081:   
                   10082:   hstepm=hstepm/stepm;
1.296     brouard  10083:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10084:   /*                              fractional in yp1 *\/ */
                   10085:   /* aintmean=yp; */
                   10086:   /* yp2=modf((yp1*12),&yp); */
                   10087:   /* mintmean=yp; */
                   10088:   /* yp1=modf((yp2*30.5),&yp); */
                   10089:   /* jintmean=yp; */
                   10090:   /* if(jintmean==0) jintmean=1; */
                   10091:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10092:   
1.351   ! brouard  10093:   /* i1=pow(2,cptcoveff); */
        !          10094:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10095:   
1.296     brouard  10096:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10097:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10098:   
                   10099:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10100:   
1.351   ! brouard  10101:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          10102:     k=TKresult[nres];
        !          10103:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
        !          10104:   /* for(k=1; k<=i1;k++){ */
        !          10105:   /*   if(i1 != 1 && TKresult[nres]!= k) */
        !          10106:   /*     continue; */
        !          10107:   /*   if(invalidvarcomb[k]){ */
        !          10108:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
        !          10109:   /*     continue; */
        !          10110:   /*   } */
1.268     brouard  10111:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351   ! brouard  10112:     for(j=1;j<=cptcovs;j++){
        !          10113:     /* for(j=1;j<=cptcoveff;j++) { */
        !          10114:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          10115:     /* } */
        !          10116:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10117:     }
1.351   ! brouard  10118:    /*  fprintf(ficrespij,"******\n"); */
        !          10119:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          10120:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          10121:    /*  } */
1.267     brouard  10122:     fprintf(ficresfb," yearbproj age");
                   10123:     for(j=1; j<=nlstate+ndeath;j++){
                   10124:       for(i=1; i<=nlstate;i++)
1.268     brouard  10125:        fprintf(ficresfb," b%d%d",i,j);
                   10126:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10127:     }
1.296     brouard  10128:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10129:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10130:       fprintf(ficresfb,"\n");
1.296     brouard  10131:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10132:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10133:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10134:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10135:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10136:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10137:        nhstepm = nhstepm/hstepm;
                   10138:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10139:        oldm=oldms;savm=savms;
1.268     brouard  10140:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10141:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10142:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10143:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10144:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10145:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10146:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10147:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10148:            break;
                   10149:          }
                   10150:        }
                   10151:        fprintf(ficresfb,"\n");
1.351   ! brouard  10152:        /* for(j=1;j<=cptcoveff;j++) */
        !          10153:        for(j=1;j<=cptcovs;j++)
        !          10154:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          10155:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10156:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10157:        for(i=1; i<=nlstate+ndeath;i++) {
                   10158:          ppij=0.;ppi=0.;
                   10159:          for(j=1; j<=nlstate;j++) {
                   10160:            /* if (mobilav==1) */
1.269     brouard  10161:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10162:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10163:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10164:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10165:              /* else { */
                   10166:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10167:              /* } */
1.268     brouard  10168:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10169:          } /* end j */
                   10170:          if(ppi <0.99){
                   10171:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10172:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10173:          }
                   10174:          fprintf(ficresfb," %.3f", ppij);
                   10175:        }/* end j */
1.267     brouard  10176:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10177:       } /* end agec */
                   10178:     } /* end yearp */
                   10179:   } /* end k */
1.217     brouard  10180:   
1.267     brouard  10181:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10182:   
1.267     brouard  10183:   fclose(ficresfb);
                   10184:   printf("End of Computing Back forecasting \n");
                   10185:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10186:        
1.267     brouard  10187: }
1.217     brouard  10188: 
1.269     brouard  10189: /* Variance of prevalence limit: varprlim */
                   10190:  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  10191:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10192:  
                   10193:    char fileresvpl[FILENAMELENGTH];  
                   10194:    FILE *ficresvpl;
                   10195:    double **oldm, **savm;
                   10196:    double **varpl; /* Variances of prevalence limits by age */   
                   10197:    int i1, k, nres, j ;
                   10198:    
                   10199:     strcpy(fileresvpl,"VPL_");
                   10200:     strcat(fileresvpl,fileresu);
                   10201:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10202:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10203:       exit(0);
                   10204:     }
1.288     brouard  10205:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10206:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10207:     
                   10208:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10209:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10210:     
                   10211:     i1=pow(2,cptcoveff);
                   10212:     if (cptcovn < 1){i1=1;}
                   10213: 
1.337     brouard  10214:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10215:        k=TKresult[nres];
1.338     brouard  10216:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10217:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10218:       if(i1 != 1 && TKresult[nres]!= k)
                   10219:        continue;
                   10220:       fprintf(ficresvpl,"\n#****** ");
                   10221:       printf("\n#****** ");
                   10222:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10223:       for(j=1;j<=cptcovs;j++) {
                   10224:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10225:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10226:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10227:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10228:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10229:       }
1.337     brouard  10230:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10231:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10232:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10233:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10234:       /* }      */
1.269     brouard  10235:       fprintf(ficresvpl,"******\n");
                   10236:       printf("******\n");
                   10237:       fprintf(ficlog,"******\n");
                   10238:       
                   10239:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10240:       oldm=oldms;savm=savms;
                   10241:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10242:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10243:       /*}*/
                   10244:     }
                   10245:     
                   10246:     fclose(ficresvpl);
1.288     brouard  10247:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10248:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10249: 
                   10250:  }
                   10251: /* Variance of back prevalence: varbprlim */
                   10252:  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){
                   10253:       /*------- Variance of back (stable) prevalence------*/
                   10254: 
                   10255:    char fileresvbl[FILENAMELENGTH];  
                   10256:    FILE  *ficresvbl;
                   10257: 
                   10258:    double **oldm, **savm;
                   10259:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10260:    int i1, k, nres, j ;
                   10261: 
                   10262:    strcpy(fileresvbl,"VBL_");
                   10263:    strcat(fileresvbl,fileresu);
                   10264:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10265:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10266:      exit(0);
                   10267:    }
                   10268:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10269:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10270:    
                   10271:    
                   10272:    i1=pow(2,cptcoveff);
                   10273:    if (cptcovn < 1){i1=1;}
                   10274:    
1.337     brouard  10275:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10276:      k=TKresult[nres];
1.338     brouard  10277:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10278:     /* for(k=1; k<=i1;k++){ */
                   10279:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10280:     /*          continue; */
1.269     brouard  10281:        fprintf(ficresvbl,"\n#****** ");
                   10282:        printf("\n#****** ");
                   10283:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10284:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10285:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10286:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10287:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10288:        /* for(j=1;j<=cptcoveff;j++) { */
                   10289:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10290:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10291:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10292:        /* } */
                   10293:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10294:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10295:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10296:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10297:        }
                   10298:        fprintf(ficresvbl,"******\n");
                   10299:        printf("******\n");
                   10300:        fprintf(ficlog,"******\n");
                   10301:        
                   10302:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10303:        oldm=oldms;savm=savms;
                   10304:        
                   10305:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10306:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10307:        /*}*/
                   10308:      }
                   10309:    
                   10310:    fclose(ficresvbl);
                   10311:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10312:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10313: 
                   10314:  } /* End of varbprlim */
                   10315: 
1.126     brouard  10316: /************** Forecasting *****not tested NB*************/
1.227     brouard  10317: /* 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  10318:   
1.227     brouard  10319: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10320: /*   int *popage; */
                   10321: /*   double calagedatem, agelim, kk1, kk2; */
                   10322: /*   double *popeffectif,*popcount; */
                   10323: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10324: /*   /\* double ***mobaverage; *\/ */
                   10325: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10326: 
1.227     brouard  10327: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10328: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10329: /*   agelim=AGESUP; */
                   10330: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10331:   
1.227     brouard  10332: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10333:   
                   10334:   
1.227     brouard  10335: /*   strcpy(filerespop,"POP_");  */
                   10336: /*   strcat(filerespop,fileresu); */
                   10337: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10338: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10339: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10340: /*   } */
                   10341: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10342: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10343: 
1.227     brouard  10344: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10345: 
1.227     brouard  10346: /*   /\* if (mobilav!=0) { *\/ */
                   10347: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10348: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10349: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10350: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10351: /*   /\*   } *\/ */
                   10352: /*   /\* } *\/ */
1.126     brouard  10353: 
1.227     brouard  10354: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10355: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10356:   
1.227     brouard  10357: /*   agelim=AGESUP; */
1.126     brouard  10358:   
1.227     brouard  10359: /*   hstepm=1; */
                   10360: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10361:        
1.227     brouard  10362: /*   if (popforecast==1) { */
                   10363: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10364: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10365: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10366: /*     }  */
                   10367: /*     popage=ivector(0,AGESUP); */
                   10368: /*     popeffectif=vector(0,AGESUP); */
                   10369: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10370:     
1.227     brouard  10371: /*     i=1;    */
                   10372: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10373:     
1.227     brouard  10374: /*     imx=i; */
                   10375: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10376: /*   } */
1.218     brouard  10377:   
1.227     brouard  10378: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10379: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10380: /*       k=k+1; */
                   10381: /*       fprintf(ficrespop,"\n#******"); */
                   10382: /*       for(j=1;j<=cptcoveff;j++) { */
                   10383: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10384: /*       } */
                   10385: /*       fprintf(ficrespop,"******\n"); */
                   10386: /*       fprintf(ficrespop,"# Age"); */
                   10387: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10388: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10389:       
1.227     brouard  10390: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10391: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10392:        
1.227     brouard  10393: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10394: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10395: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10396:          
1.227     brouard  10397: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10398: /*       oldm=oldms;savm=savms; */
                   10399: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10400:          
1.227     brouard  10401: /*       for (h=0; h<=nhstepm; h++){ */
                   10402: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10403: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10404: /*         }  */
                   10405: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10406: /*           kk1=0.;kk2=0; */
                   10407: /*           for(i=1; i<=nlstate;i++) {               */
                   10408: /*             if (mobilav==1)  */
                   10409: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10410: /*             else { */
                   10411: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10412: /*             } */
                   10413: /*           } */
                   10414: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10415: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10416: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10417: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10418: /*           } */
                   10419: /*         } */
                   10420: /*         for(i=1; i<=nlstate;i++){ */
                   10421: /*           kk1=0.; */
                   10422: /*           for(j=1; j<=nlstate;j++){ */
                   10423: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10424: /*           } */
                   10425: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10426: /*         } */
1.218     brouard  10427:            
1.227     brouard  10428: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10429: /*           for(j=1; j<=nlstate;j++)  */
                   10430: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10431: /*       } */
                   10432: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10433: /*     } */
                   10434: /*       } */
1.218     brouard  10435:       
1.227     brouard  10436: /*       /\******\/ */
1.218     brouard  10437:       
1.227     brouard  10438: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10439: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10440: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10441: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10442: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10443:          
1.227     brouard  10444: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10445: /*       oldm=oldms;savm=savms; */
                   10446: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10447: /*       for (h=0; h<=nhstepm; h++){ */
                   10448: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10449: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10450: /*         }  */
                   10451: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10452: /*           kk1=0.;kk2=0; */
                   10453: /*           for(i=1; i<=nlstate;i++) {               */
                   10454: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10455: /*           } */
                   10456: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10457: /*         } */
                   10458: /*       } */
                   10459: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10460: /*     } */
                   10461: /*       } */
                   10462: /*     }  */
                   10463: /*   } */
1.218     brouard  10464:   
1.227     brouard  10465: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10466:   
1.227     brouard  10467: /*   if (popforecast==1) { */
                   10468: /*     free_ivector(popage,0,AGESUP); */
                   10469: /*     free_vector(popeffectif,0,AGESUP); */
                   10470: /*     free_vector(popcount,0,AGESUP); */
                   10471: /*   } */
                   10472: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10473: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10474: /*   fclose(ficrespop); */
                   10475: /* } /\* End of popforecast *\/ */
1.218     brouard  10476:  
1.126     brouard  10477: int fileappend(FILE *fichier, char *optionfich)
                   10478: {
                   10479:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10480:     printf("Problem with file: %s\n", optionfich);
                   10481:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10482:     return (0);
                   10483:   }
                   10484:   fflush(fichier);
                   10485:   return (1);
                   10486: }
                   10487: 
                   10488: 
                   10489: /**************** function prwizard **********************/
                   10490: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10491: {
                   10492: 
                   10493:   /* Wizard to print covariance matrix template */
                   10494: 
1.164     brouard  10495:   char ca[32], cb[32];
                   10496:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10497:   int numlinepar;
                   10498: 
                   10499:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10500:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10501:   for(i=1; i <=nlstate; i++){
                   10502:     jj=0;
                   10503:     for(j=1; j <=nlstate+ndeath; j++){
                   10504:       if(j==i) continue;
                   10505:       jj++;
                   10506:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10507:       printf("%1d%1d",i,j);
                   10508:       fprintf(ficparo,"%1d%1d",i,j);
                   10509:       for(k=1; k<=ncovmodel;k++){
                   10510:        /*        printf(" %lf",param[i][j][k]); */
                   10511:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10512:        printf(" 0.");
                   10513:        fprintf(ficparo," 0.");
                   10514:       }
                   10515:       printf("\n");
                   10516:       fprintf(ficparo,"\n");
                   10517:     }
                   10518:   }
                   10519:   printf("# Scales (for hessian or gradient estimation)\n");
                   10520:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10521:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10522:   for(i=1; i <=nlstate; i++){
                   10523:     jj=0;
                   10524:     for(j=1; j <=nlstate+ndeath; j++){
                   10525:       if(j==i) continue;
                   10526:       jj++;
                   10527:       fprintf(ficparo,"%1d%1d",i,j);
                   10528:       printf("%1d%1d",i,j);
                   10529:       fflush(stdout);
                   10530:       for(k=1; k<=ncovmodel;k++){
                   10531:        /*      printf(" %le",delti3[i][j][k]); */
                   10532:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10533:        printf(" 0.");
                   10534:        fprintf(ficparo," 0.");
                   10535:       }
                   10536:       numlinepar++;
                   10537:       printf("\n");
                   10538:       fprintf(ficparo,"\n");
                   10539:     }
                   10540:   }
                   10541:   printf("# Covariance matrix\n");
                   10542: /* # 121 Var(a12)\n\ */
                   10543: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10544: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10545: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10546: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10547: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10548: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10549: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10550:   fflush(stdout);
                   10551:   fprintf(ficparo,"# Covariance matrix\n");
                   10552:   /* # 121 Var(a12)\n\ */
                   10553:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10554:   /* #   ...\n\ */
                   10555:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10556:   
                   10557:   for(itimes=1;itimes<=2;itimes++){
                   10558:     jj=0;
                   10559:     for(i=1; i <=nlstate; i++){
                   10560:       for(j=1; j <=nlstate+ndeath; j++){
                   10561:        if(j==i) continue;
                   10562:        for(k=1; k<=ncovmodel;k++){
                   10563:          jj++;
                   10564:          ca[0]= k+'a'-1;ca[1]='\0';
                   10565:          if(itimes==1){
                   10566:            printf("#%1d%1d%d",i,j,k);
                   10567:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10568:          }else{
                   10569:            printf("%1d%1d%d",i,j,k);
                   10570:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10571:            /*  printf(" %.5le",matcov[i][j]); */
                   10572:          }
                   10573:          ll=0;
                   10574:          for(li=1;li <=nlstate; li++){
                   10575:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10576:              if(lj==li) continue;
                   10577:              for(lk=1;lk<=ncovmodel;lk++){
                   10578:                ll++;
                   10579:                if(ll<=jj){
                   10580:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10581:                  if(ll<jj){
                   10582:                    if(itimes==1){
                   10583:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10584:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10585:                    }else{
                   10586:                      printf(" 0.");
                   10587:                      fprintf(ficparo," 0.");
                   10588:                    }
                   10589:                  }else{
                   10590:                    if(itimes==1){
                   10591:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10592:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10593:                    }else{
                   10594:                      printf(" 0.");
                   10595:                      fprintf(ficparo," 0.");
                   10596:                    }
                   10597:                  }
                   10598:                }
                   10599:              } /* end lk */
                   10600:            } /* end lj */
                   10601:          } /* end li */
                   10602:          printf("\n");
                   10603:          fprintf(ficparo,"\n");
                   10604:          numlinepar++;
                   10605:        } /* end k*/
                   10606:       } /*end j */
                   10607:     } /* end i */
                   10608:   } /* end itimes */
                   10609: 
                   10610: } /* end of prwizard */
                   10611: /******************* Gompertz Likelihood ******************************/
                   10612: double gompertz(double x[])
                   10613: { 
1.302     brouard  10614:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10615:   int i,n=0; /* n is the size of the sample */
                   10616: 
1.220     brouard  10617:   for (i=1;i<=imx ; i++) {
1.126     brouard  10618:     sump=sump+weight[i];
                   10619:     /*    sump=sump+1;*/
                   10620:     num=num+1;
                   10621:   }
1.302     brouard  10622:   L=0.0;
                   10623:   /* agegomp=AGEGOMP; */
1.126     brouard  10624:   /* for (i=0; i<=imx; i++) 
                   10625:      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]);*/
                   10626: 
1.302     brouard  10627:   for (i=1;i<=imx ; i++) {
                   10628:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10629:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10630:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10631:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10632:      * +
                   10633:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10634:      */
                   10635:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10636:        if (cens[i] == 1){
                   10637:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10638:        } else if (cens[i] == 0){
1.126     brouard  10639:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10640:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10641:       } else
                   10642:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10643:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10644:        L=L+A*weight[i];
1.126     brouard  10645:        /*      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  10646:      }
                   10647:   }
1.126     brouard  10648: 
1.302     brouard  10649:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10650:  
                   10651:   return -2*L*num/sump;
                   10652: }
                   10653: 
1.136     brouard  10654: #ifdef GSL
                   10655: /******************* Gompertz_f Likelihood ******************************/
                   10656: double gompertz_f(const gsl_vector *v, void *params)
                   10657: { 
1.302     brouard  10658:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10659:   double *x= (double *) v->data;
                   10660:   int i,n=0; /* n is the size of the sample */
                   10661: 
                   10662:   for (i=0;i<=imx-1 ; i++) {
                   10663:     sump=sump+weight[i];
                   10664:     /*    sump=sump+1;*/
                   10665:     num=num+1;
                   10666:   }
                   10667:  
                   10668:  
                   10669:   /* for (i=0; i<=imx; i++) 
                   10670:      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]);*/
                   10671:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10672:   for (i=1;i<=imx ; i++)
                   10673:     {
                   10674:       if (cens[i] == 1 && wav[i]>1)
                   10675:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10676:       
                   10677:       if (cens[i] == 0 && wav[i]>1)
                   10678:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10679:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10680:       
                   10681:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10682:       if (wav[i] > 1 ) { /* ??? */
                   10683:        LL=LL+A*weight[i];
                   10684:        /*      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]);*/
                   10685:       }
                   10686:     }
                   10687: 
                   10688:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10689:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10690:  
                   10691:   return -2*LL*num/sump;
                   10692: }
                   10693: #endif
                   10694: 
1.126     brouard  10695: /******************* Printing html file ***********/
1.201     brouard  10696: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10697:                  int lastpass, int stepm, int weightopt, char model[],\
                   10698:                  int imx,  double p[],double **matcov,double agemortsup){
                   10699:   int i,k;
                   10700: 
                   10701:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10702:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10703:   for (i=1;i<=2;i++) 
                   10704:     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  10705:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10706:   fprintf(fichtm,"</ul>");
                   10707: 
                   10708: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10709: 
                   10710:  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>");
                   10711: 
                   10712:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10713:    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]);
                   10714: 
                   10715:  
                   10716:   fflush(fichtm);
                   10717: }
                   10718: 
                   10719: /******************* Gnuplot file **************/
1.201     brouard  10720: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10721: 
                   10722:   char dirfileres[132],optfileres[132];
1.164     brouard  10723: 
1.126     brouard  10724:   int ng;
                   10725: 
                   10726: 
                   10727:   /*#ifdef windows */
                   10728:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10729:     /*#endif */
                   10730: 
                   10731: 
                   10732:   strcpy(dirfileres,optionfilefiname);
                   10733:   strcpy(optfileres,"vpl");
1.199     brouard  10734:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10735:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10736:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10737:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10738:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10739: 
                   10740: } 
                   10741: 
1.136     brouard  10742: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10743: {
1.126     brouard  10744: 
1.136     brouard  10745:   /*-------- data file ----------*/
                   10746:   FILE *fic;
                   10747:   char dummy[]="                         ";
1.240     brouard  10748:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10749:   int lstra;
1.136     brouard  10750:   int linei, month, year,iout;
1.302     brouard  10751:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10752:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10753:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10754:   char *stratrunc;
1.223     brouard  10755: 
1.349     brouard  10756:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10757:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10758:   
                   10759:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10760:   
1.136     brouard  10761:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10762:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10763:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10764:   }
1.126     brouard  10765: 
1.302     brouard  10766:     /* Is it a BOM UTF-8 Windows file? */
                   10767:   /* First data line */
                   10768:   linei=0;
                   10769:   while(fgets(line, MAXLINE, fic)) {
                   10770:     noffset=0;
                   10771:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10772:     {
                   10773:       noffset=noffset+3;
                   10774:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10775:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10776:       fflush(ficlog); return 1;
                   10777:     }
                   10778:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10779:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10780:     {
                   10781:       noffset=noffset+2;
1.304     brouard  10782:       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);
                   10783:       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  10784:       fflush(ficlog); return 1;
                   10785:     }
                   10786:     else if( line[0] == 0 && line[1] == 0)
                   10787:     {
                   10788:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10789:        noffset=noffset+4;
1.304     brouard  10790:        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);
                   10791:        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  10792:        fflush(ficlog); return 1;
                   10793:       }
                   10794:     } else{
                   10795:       ;/*printf(" Not a BOM file\n");*/
                   10796:     }
                   10797:         /* If line starts with a # it is a comment */
                   10798:     if (line[noffset] == '#') {
                   10799:       linei=linei+1;
                   10800:       break;
                   10801:     }else{
                   10802:       break;
                   10803:     }
                   10804:   }
                   10805:   fclose(fic);
                   10806:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10807:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10808:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10809:   }
                   10810:   /* Not a Bom file */
                   10811:   
1.136     brouard  10812:   i=1;
                   10813:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10814:     linei=linei+1;
                   10815:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10816:       if(line[j] == '\t')
                   10817:        line[j] = ' ';
                   10818:     }
                   10819:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10820:       ;
                   10821:     };
                   10822:     line[j+1]=0;  /* Trims blanks at end of line */
                   10823:     if(line[0]=='#'){
                   10824:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10825:       printf("Comment line\n%s\n",line);
                   10826:       continue;
                   10827:     }
                   10828:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10829:     strcpy(line, linetmp);
1.223     brouard  10830:     
                   10831:     /* Loops on waves */
                   10832:     for (j=maxwav;j>=1;j--){
                   10833:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10834:        cutv(stra, strb, line, ' '); 
                   10835:        if(strb[0]=='.') { /* Missing value */
                   10836:          lval=-1;
                   10837:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10838:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10839:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10840:            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);
                   10841:            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);
                   10842:            return 1;
                   10843:          }
                   10844:        }else{
                   10845:          errno=0;
                   10846:          /* what_kind_of_number(strb); */
                   10847:          dval=strtod(strb,&endptr); 
                   10848:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10849:          /* if(strb != endptr && *endptr == '\0') */
                   10850:          /*    dval=dlval; */
                   10851:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10852:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10853:            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);
                   10854:            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);
                   10855:            return 1;
                   10856:          }
                   10857:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10858:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10859:        }
                   10860:        strcpy(line,stra);
1.223     brouard  10861:       }/* end loop ntqv */
1.225     brouard  10862:       
1.223     brouard  10863:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10864:        cutv(stra, strb, line, ' '); 
                   10865:        if(strb[0]=='.') { /* Missing value */
                   10866:          lval=-1;
                   10867:        }else{
                   10868:          errno=0;
                   10869:          lval=strtol(strb,&endptr,10); 
                   10870:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10871:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10872:            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);
                   10873:            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);
                   10874:            return 1;
                   10875:          }
                   10876:        }
                   10877:        if(lval <-1 || lval >1){
                   10878:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10879:  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  10880:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10881:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10882:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10883:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10884:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10885:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10886:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10887:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10888:  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  10889:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10890:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10891:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10892:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10893:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10894:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10895:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10896:          return 1;
                   10897:        }
1.341     brouard  10898:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10899:        strcpy(line,stra);
1.223     brouard  10900:       }/* end loop ntv */
1.225     brouard  10901:       
1.223     brouard  10902:       /* Statuses  at wave */
1.137     brouard  10903:       cutv(stra, strb, line, ' '); 
1.223     brouard  10904:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10905:        lval=-1;
1.136     brouard  10906:       }else{
1.238     brouard  10907:        errno=0;
                   10908:        lval=strtol(strb,&endptr,10); 
                   10909:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10910:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10911:          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);
                   10912:          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);
                   10913:          return 1;
                   10914:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10915:          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);
                   10916:          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  10917:          return 1;
                   10918:        }
1.136     brouard  10919:       }
1.225     brouard  10920:       
1.136     brouard  10921:       s[j][i]=lval;
1.225     brouard  10922:       
1.223     brouard  10923:       /* Date of Interview */
1.136     brouard  10924:       strcpy(line,stra);
                   10925:       cutv(stra, strb,line,' ');
1.169     brouard  10926:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10927:       }
1.169     brouard  10928:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10929:        month=99;
                   10930:        year=9999;
1.136     brouard  10931:       }else{
1.225     brouard  10932:        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);
                   10933:        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);
                   10934:        return 1;
1.136     brouard  10935:       }
                   10936:       anint[j][i]= (double) year; 
1.302     brouard  10937:       mint[j][i]= (double)month;
                   10938:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10939:       /*       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]); */
                   10940:       /*       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]); */
                   10941:       /* } */
1.136     brouard  10942:       strcpy(line,stra);
1.223     brouard  10943:     } /* End loop on waves */
1.225     brouard  10944:     
1.223     brouard  10945:     /* Date of death */
1.136     brouard  10946:     cutv(stra, strb,line,' '); 
1.169     brouard  10947:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10948:     }
1.169     brouard  10949:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10950:       month=99;
                   10951:       year=9999;
                   10952:     }else{
1.141     brouard  10953:       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  10954:       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);
                   10955:       return 1;
1.136     brouard  10956:     }
                   10957:     andc[i]=(double) year; 
                   10958:     moisdc[i]=(double) month; 
                   10959:     strcpy(line,stra);
                   10960:     
1.223     brouard  10961:     /* Date of birth */
1.136     brouard  10962:     cutv(stra, strb,line,' '); 
1.169     brouard  10963:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10964:     }
1.169     brouard  10965:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10966:       month=99;
                   10967:       year=9999;
                   10968:     }else{
1.141     brouard  10969:       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);
                   10970:       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  10971:       return 1;
1.136     brouard  10972:     }
                   10973:     if (year==9999) {
1.141     brouard  10974:       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);
                   10975:       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  10976:       return 1;
                   10977:       
1.136     brouard  10978:     }
                   10979:     annais[i]=(double)(year);
1.302     brouard  10980:     moisnais[i]=(double)(month);
                   10981:     for (j=1;j<=maxwav;j++){
                   10982:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10983:        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]);
                   10984:        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]);
                   10985:       }
                   10986:     }
                   10987: 
1.136     brouard  10988:     strcpy(line,stra);
1.225     brouard  10989:     
1.223     brouard  10990:     /* Sample weight */
1.136     brouard  10991:     cutv(stra, strb,line,' '); 
                   10992:     errno=0;
                   10993:     dval=strtod(strb,&endptr); 
                   10994:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10995:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10996:       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  10997:       fflush(ficlog);
                   10998:       return 1;
                   10999:     }
                   11000:     weight[i]=dval; 
                   11001:     strcpy(line,stra);
1.225     brouard  11002:     
1.223     brouard  11003:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11004:       cutv(stra, strb, line, ' '); 
                   11005:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11006:        lval=-1;
1.311     brouard  11007:        coqvar[iv][i]=NAN; 
                   11008:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11009:       }else{
1.225     brouard  11010:        errno=0;
                   11011:        /* what_kind_of_number(strb); */
                   11012:        dval=strtod(strb,&endptr);
                   11013:        /* if(strb != endptr && *endptr == '\0') */
                   11014:        /*   dval=dlval; */
                   11015:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11016:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11017:          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);
                   11018:          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);
                   11019:          return 1;
                   11020:        }
                   11021:        coqvar[iv][i]=dval; 
1.226     brouard  11022:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11023:       }
                   11024:       strcpy(line,stra);
                   11025:     }/* end loop nqv */
1.136     brouard  11026:     
1.223     brouard  11027:     /* Covariate values */
1.136     brouard  11028:     for (j=ncovcol;j>=1;j--){
                   11029:       cutv(stra, strb,line,' '); 
1.223     brouard  11030:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11031:        lval=-1;
1.136     brouard  11032:       }else{
1.225     brouard  11033:        errno=0;
                   11034:        lval=strtol(strb,&endptr,10); 
                   11035:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11036:          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);
                   11037:          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);
                   11038:          return 1;
                   11039:        }
1.136     brouard  11040:       }
                   11041:       if(lval <-1 || lval >1){
1.225     brouard  11042:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11043:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11044:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11045:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11046:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11047:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11048:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11049:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11050:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11051:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11052:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11053:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11054:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11055:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11056:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11057:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11058:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11059:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11060:        return 1;
1.136     brouard  11061:       }
                   11062:       covar[j][i]=(double)(lval);
                   11063:       strcpy(line,stra);
                   11064:     }  
                   11065:     lstra=strlen(stra);
1.225     brouard  11066:     
1.136     brouard  11067:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11068:       stratrunc = &(stra[lstra-9]);
                   11069:       num[i]=atol(stratrunc);
                   11070:     }
                   11071:     else
                   11072:       num[i]=atol(stra);
                   11073:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11074:       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;}*/
                   11075:     
                   11076:     i=i+1;
                   11077:   } /* End loop reading  data */
1.225     brouard  11078:   
1.136     brouard  11079:   *imax=i-1; /* Number of individuals */
                   11080:   fclose(fic);
1.225     brouard  11081:   
1.136     brouard  11082:   return (0);
1.164     brouard  11083:   /* endread: */
1.225     brouard  11084:   printf("Exiting readdata: ");
                   11085:   fclose(fic);
                   11086:   return (1);
1.223     brouard  11087: }
1.126     brouard  11088: 
1.234     brouard  11089: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11090:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11091:   while (*p2 == ' ')
1.234     brouard  11092:     p2++; 
                   11093:   /* while ((*p1++ = *p2++) !=0) */
                   11094:   /*   ; */
                   11095:   /* do */
                   11096:   /*   while (*p2 == ' ') */
                   11097:   /*     p2++; */
                   11098:   /* while (*p1++ == *p2++); */
                   11099:   *stri=p2; 
1.145     brouard  11100: }
                   11101: 
1.330     brouard  11102: int decoderesult( char resultline[], int nres)
1.230     brouard  11103: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11104: {
1.235     brouard  11105:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11106:   char resultsav[MAXLINE];
1.330     brouard  11107:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11108:   /* int modelresult[MAXLINE]; */
1.230     brouard  11109:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11110: 
1.234     brouard  11111:   removefirstspace(&resultline);
1.332     brouard  11112:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11113: 
1.332     brouard  11114:   strcpy(resultsav,resultline);
1.342     brouard  11115:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11116:   if (strlen(resultsav) >1){
1.334     brouard  11117:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11118:   }
1.253     brouard  11119:   if(j == 0){ /* Resultline but no = */
                   11120:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11121:     return (0);
                   11122:   }
1.234     brouard  11123:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  11124:     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);
                   11125:     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  11126:     /* return 1;*/
1.234     brouard  11127:   }
1.334     brouard  11128:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11129:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11130:       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  11131:       /* 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  11132:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11133:       /* If a blank, then strc="V4=" and strd='\0' */
                   11134:       if(strc[0]=='\0'){
                   11135:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11136:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11137:        return 1;
                   11138:       }
1.234     brouard  11139:     }else
                   11140:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11141:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11142:     
1.230     brouard  11143:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11144:     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  11145:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11146:     /* cptcovsel++;     */
                   11147:     if (nbocc(stra,'=') >0)
                   11148:       strcpy(resultsav,stra); /* and analyzes it */
                   11149:   }
1.235     brouard  11150:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11151:   /* 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  11152:   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  11153:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11154:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11155:       match=0;
1.318     brouard  11156:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11157:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11158:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11159:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11160:          break;
                   11161:        }
                   11162:       }
                   11163:       if(match == 0){
1.338     brouard  11164:        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]);
                   11165:        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  11166:        return 1;
1.234     brouard  11167:       }
1.332     brouard  11168:     }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*/
                   11169:       /* We feed resultmodel[k1]=k2; */
                   11170:       match=0;
                   11171:       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 */
                   11172:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11173:          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  11174:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11175:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11176:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11177:          break;
                   11178:        }
                   11179:       }
                   11180:       if(match == 0){
1.338     brouard  11181:        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]);
                   11182:        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  11183:       return 1;
                   11184:       }
1.349     brouard  11185:     }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  11186:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11187:       match=0;
1.342     brouard  11188:       /* 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  11189:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11190:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11191:          /* modelresult[k2]=k1; */
1.342     brouard  11192:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11193:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11194:        }
                   11195:       }
                   11196:       if(match == 0){
1.349     brouard  11197:        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);
                   11198:        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  11199:        return 1;
                   11200:       }
                   11201:       match=0;
                   11202:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11203:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11204:          /* modelresult[k2]=k1;*/
1.342     brouard  11205:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11206:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11207:          break;
                   11208:        }
                   11209:       }
                   11210:       if(match == 0){
1.349     brouard  11211:        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);
                   11212:        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  11213:        return 1;
                   11214:       }
                   11215:     }/* End of testing */
1.333     brouard  11216:   }/* End loop cptcovt */
1.235     brouard  11217:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11218:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11219:   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)
                   11220:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11221:     match=0;
1.318     brouard  11222:     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  11223:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11224:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11225:          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  11226:          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  11227:          ++match;
                   11228:        }
                   11229:       }
                   11230:     }
                   11231:     if(match == 0){
1.338     brouard  11232:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11233:       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  11234:       return 1;
1.234     brouard  11235:     }else if(match > 1){
1.338     brouard  11236:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11237:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11238:       return 1;
1.234     brouard  11239:     }
                   11240:   }
1.334     brouard  11241:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11242:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11243:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11244:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11245:   /* 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*/
                   11246:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11247:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11248:   /*    1 0 0 0 */
                   11249:   /*    2 1 0 0 */
                   11250:   /*    3 0 1 0 */ 
1.330     brouard  11251:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11252:   /*    5 0 0 1 */
1.330     brouard  11253:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11254:   /*    7 0 1 1 */
                   11255:   /*    8 1 1 1 */
1.237     brouard  11256:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11257:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11258:   /* V5*age V5 known which value for nres?  */
                   11259:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11260:   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.
                   11261:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11262:     /* k counting number of combination of single dummies in the equation model */
                   11263:     /* k4 counting single dummies in the equation model */
                   11264:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11265:     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  11266:        /* 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  11267:       /* 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  11268:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11269:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11270:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11271:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11272:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11273:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11274:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11275:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11276:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11277:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11278:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11279:       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  11280:       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  11281:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11282:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11283:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11284:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11285:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11286:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11287:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11288:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11289:       /* 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  11290:       k4++;;
1.331     brouard  11291:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11292:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11293:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11294:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11295:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11296:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11297:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11298:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11299:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11300:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11301:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11302:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11303:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11304:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11305:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11306:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11307:       /* 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  11308:       k4q++;;
1.350     brouard  11309:     }else if( Dummy[k1]==2 ){ /* For dummy with age product "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+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   11310:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11311:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11312:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11313:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11314:       /* 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]]); */
                   11315:       }else{
                   11316:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11317:        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)*/
                   11318:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11319:        precov[nres][k1]=Tvalsel[k3];
                   11320:       }
1.342     brouard  11321:       /* 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  11322:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11323:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11324:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11325:       /* 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]]); */
                   11326:       }else{
                   11327:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11328:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11329:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11330:        precov[nres][k1]=Tvalsel[k3q];
                   11331:       }
1.342     brouard  11332:       /* 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  11333:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11334:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11335:       /* 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  11336:     }else{
1.332     brouard  11337:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11338:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11339:     }
                   11340:   }
1.234     brouard  11341:   
1.334     brouard  11342:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11343:   return (0);
                   11344: }
1.235     brouard  11345: 
1.230     brouard  11346: int decodemodel( char model[], int lastobs)
                   11347:  /**< This routine decodes the model and returns:
1.224     brouard  11348:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11349:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11350:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11351:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11352:        * - cptcovage number of covariates with age*products =2
                   11353:        * - cptcovs number of simple covariates
1.339     brouard  11354:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11355:        * - 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  11356:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11357:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11358:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11359:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11360:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11361:        */
1.319     brouard  11362: /* 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  11363: {
1.238     brouard  11364:   int i, j, k, ks, v;
1.349     brouard  11365:   int n,m;
                   11366:   int  j1, k1, k11, k12, k2, k3, k4;
                   11367:   char modelsav[300];
                   11368:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11369:   char *strpt;
1.349     brouard  11370:   int  **existcomb;
                   11371:   
                   11372:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11373:   for(i=1;i<=NCOVMAX;i++)
                   11374:     for(j=1;j<=NCOVMAX;j++)
                   11375:       existcomb[i][j]=0;
                   11376:     
1.145     brouard  11377:   /*removespace(model);*/
1.136     brouard  11378:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11379:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11380:     if (strstr(model,"AGE") !=0){
1.192     brouard  11381:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11382:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11383:       return 1;
                   11384:     }
1.141     brouard  11385:     if (strstr(model,"v") !=0){
1.338     brouard  11386:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11387:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11388:       return 1;
                   11389:     }
1.187     brouard  11390:     strcpy(modelsav,model); 
                   11391:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11392:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11393:       if(strpt != model){
1.338     brouard  11394:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11395:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11396:  corresponding column of parameters.\n",model);
1.338     brouard  11397:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11398:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11399:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11400:        return 1;
1.225     brouard  11401:       }
1.187     brouard  11402:       nagesqr=1;
                   11403:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11404:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11405:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11406:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11407:       else 
1.234     brouard  11408:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11409:     }else
                   11410:       nagesqr=0;
1.349     brouard  11411:     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  11412:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11413:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351   ! brouard  11414:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11415:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11416:                     * cst, age and age*age 
                   11417:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11418:       /* including age products which are counted in cptcovage.
                   11419:        * but the covariates which are products must be treated 
                   11420:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11421:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11422:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11423:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11424:       cptcovprodage=0;
                   11425:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11426:       
1.187     brouard  11427:       /*   Design
                   11428:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11429:        *  <          ncovcol=8                >
                   11430:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11431:        *   k=  1    2      3       4     5       6      7        8
                   11432:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11433:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11434:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11435:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11436:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11437:        *  Tage[++cptcovage]=k
1.345     brouard  11438:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11439:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11440:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11441:        *  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
                   11442:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11443:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11444:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11445:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11446:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11447:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11448:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11449:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11450:        * p Tprod[1]@2={                         6, 5}
                   11451:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11452:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11453:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11454:        *How to reorganize? Tvars(orted)
1.187     brouard  11455:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11456:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11457:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11458:        * Struct []
                   11459:        */
1.225     brouard  11460:       
1.187     brouard  11461:       /* This loop fills the array Tvar from the string 'model'.*/
                   11462:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11463:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11464:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11465:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11466:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11467:       /*       k=1 Tvar[1]=2 (from V2) */
                   11468:       /*       k=5 Tvar[5] */
                   11469:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11470:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11471:       /*       } */
1.198     brouard  11472:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11473:       /*
                   11474:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11475:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11476:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11477:       }
1.187     brouard  11478:       cptcovage=0;
1.351   ! brouard  11479: 
        !          11480:       /* First loop in order to calculate */
        !          11481:       /* for age*VN*Vm
        !          11482:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
        !          11483:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
        !          11484:       */
        !          11485:       /* Needs  FixedV[Tvardk[k][1]] */
        !          11486:       /* For others:
        !          11487:        * Sets  Typevar[k];
        !          11488:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
        !          11489:        *       Tposprod[k]=k11;
        !          11490:        *       Tprod[k11]=k;
        !          11491:        *       Tvardk[k][1] =m;
        !          11492:        * Needs FixedV[Tvardk[k][1]] == 0
        !          11493:       */
        !          11494:       
1.319     brouard  11495:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11496:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11497:                                         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" */
                   11498:        if (nbocc(modelsav,'+')==0)
                   11499:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11500:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11501:        /*scanf("%d",i);*/
1.349     brouard  11502:        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 */
                   11503:          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  */
                   11504:          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   */
                   11505:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11506:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11507:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11508:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11509:              /* We want strb=Vn*Vm */
                   11510:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11511:                 strcpy(strb,strd);
                   11512:                 strcat(strb,"*");
                   11513:                 strcat(strb,stre);
                   11514:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11515:                 strcpy(strb,strf);
                   11516:                 strcat(strb,"*");
                   11517:                 strcat(strb,stre);
                   11518:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11519:               }
1.351   ! brouard  11520:              /* 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]]]); */
        !          11521:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11522:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11523:              strcpy(stre,strb); /* save full b in stre */
                   11524:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11525:              strcpy(strf,strc); /* save short c in new short f */
                   11526:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11527:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11528:             }
                   11529:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11530:             /* 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 *\/ */
                   11531:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11532:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11533:            n=atoi(stre);
1.234     brouard  11534:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11535:            m=atoi(strc);
                   11536:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11537:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11538:            if(existcomb[n][m] == 0){
                   11539:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11540:              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);
                   11541:              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);
                   11542:              fflush(ficlog);
                   11543:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11544:              k12++;
                   11545:              existcomb[n][m]=k1;
                   11546:              existcomb[m][n]=k1;
                   11547:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11548:              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*/
                   11549:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11550:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11551:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11552:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11553:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351   ! brouard  11554: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11555:              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 */
                   11556:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11557:                  /* Computes the new covariate which is a product of
                   11558:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11559:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11560:                }
                   11561:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11562:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11563:                k12++;
                   11564:                FixedV[ncovcolt+k12]=0;
                   11565:              }else{ /*End of FixedV */
                   11566:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11567:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11568:                k12++;
                   11569:                FixedV[ncovcolt+k12]=1;
                   11570:              }
                   11571:            }else{  /* k1 Vn*Vm already exists */
                   11572:              k11=existcomb[n][m];
                   11573:              Tposprod[k]=k11; /* OK */
                   11574:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11575:              Tvardk[k][1]=m;
                   11576:              Tvardk[k][2]=n;
                   11577:              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 */
                   11578:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11579:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11580:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11581:                Tvar[Tage[cptcovage]]=k1;
                   11582:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11583:                k12++;
                   11584:                FixedV[ncovcolt+k12]=0;
                   11585:              }else{ /* Already exists but time varying (and age) */
                   11586:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11587:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11588:                /* Tvar[Tage[cptcovage]]=k1; */
                   11589:                cptcovprodvage++;
                   11590:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11591:                k12++;
                   11592:                FixedV[ncovcolt+k12]=1;
                   11593:              }
                   11594:            }
                   11595:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11596:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11597:          } 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 */
                   11598:             cptcovprod++;
                   11599:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11600:               /* covar is not filled and then is empty */
                   11601:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11602:               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 */
                   11603:               Typevar[k]=1;  /* 1 for age product */
                   11604:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11605:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11606:              if( FixedV[Tvar[k]] == 0){
                   11607:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11608:              }else{
                   11609:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11610:              }
                   11611:               /*printf("stre=%s ", stre);*/
                   11612:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11613:               cutl(stre,strb,strc,'V');
                   11614:               Tvar[k]=atoi(stre);
                   11615:               Typevar[k]=1;  /* 1 for age product */
                   11616:               cptcovage++;
                   11617:               Tage[cptcovage]=k;
                   11618:              if( FixedV[Tvar[k]] == 0){
                   11619:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11620:              }else{
                   11621:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11622:              }
1.349     brouard  11623:             }else{ /*  for product Vn*Vm */
                   11624:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11625:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11626:              n=atoi(stre);
                   11627:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11628:              m=atoi(strc);
                   11629:              k1++;
                   11630:              cptcovprodnoage++;
                   11631:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11632:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11633:                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]);
                   11634:                fflush(ficlog);
                   11635:                k11=existcomb[n][m];
                   11636:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11637:                Tposprod[k]=k11;
                   11638:                Tprod[k11]=k;
                   11639:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11640:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11641:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11642:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11643:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11644:                existcomb[n][m]=k1;
                   11645:                existcomb[m][n]=k1;
                   11646:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11647:                                                    because this model-covariate is a construction we invent a new column
                   11648:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11649:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11650:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11651:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11652:                /* Please remark that the new variables are model dependent */
                   11653:                /* If we have 4 variable but the model uses only 3, like in
                   11654:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11655:                 *  k=     1     2      3   4     5        6        7       8
                   11656:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11657:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11658:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11659:                 */
                   11660:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11661:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11662:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11663:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11664:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11665:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11666:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11667:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11668:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11669:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11670:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11671:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11672:                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 */
                   11673:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11674:                    /* Computes the new covariate which is a product of
                   11675:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11676:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11677:                  }
                   11678:                  /* TvarVV[k2]=n; */
                   11679:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11680:                  /* TvarVV[k2+1]=m; */
                   11681:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11682:                }else{ /* not FixedV */
                   11683:                  /* TvarVV[k2]=n; */
                   11684:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11685:                  /* TvarVV[k2+1]=m; */
                   11686:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11687:                }                 
                   11688:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11689:            } /*  End of product Vn*Vm */
                   11690:           } /* End of age*double product or simple product */
                   11691:        }else { /* not a product */
1.234     brouard  11692:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11693:          /*  scanf("%d",i);*/
                   11694:          cutl(strd,strc,strb,'V');
                   11695:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11696:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11697:          Tvar[k]=atoi(strd);
                   11698:          Typevar[k]=0;  /* 0 for simple covariates */
                   11699:        }
                   11700:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11701:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11702:                                  scanf("%d",i);*/
1.187     brouard  11703:       } /* end of loop + on total covariates */
1.351   ! brouard  11704: 
        !          11705:       
1.187     brouard  11706:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11707:   } /* end if strlen(model == 0) */
1.349     brouard  11708:   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  */
                   11709: 
1.136     brouard  11710:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11711:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11712:   
1.136     brouard  11713:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11714:      printf("cptcovprod=%d ", cptcovprod);
                   11715:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11716:      scanf("%d ",i);*/
                   11717: 
                   11718: 
1.230     brouard  11719: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11720:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11721: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11722:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11723:    k =           1    2   3     4       5       6      7      8        9
                   11724:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11725:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11726:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11727:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11728:          Tmodelind[combination of covar]=k;
1.225     brouard  11729: */  
                   11730: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11731:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11732:   /* 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  11733:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11734:   printf("Model=1+age+%s\n\
1.349     brouard  11735: 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  11736: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11737: 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  11738:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11739: 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  11740: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11741: 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  11742:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11743:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351   ! brouard  11744: 
        !          11745: 
        !          11746:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
        !          11747: 
        !          11748:   
1.349     brouard  11749:   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  11750:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11751:       Fixed[k]= 0;
                   11752:       Dummy[k]= 0;
1.225     brouard  11753:       ncoveff++;
1.232     brouard  11754:       ncovf++;
1.234     brouard  11755:       nsd++;
                   11756:       modell[k].maintype= FTYPE;
                   11757:       TvarsD[nsd]=Tvar[k];
                   11758:       TvarsDind[nsd]=k;
1.330     brouard  11759:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11760:       TvarF[ncovf]=Tvar[k];
                   11761:       TvarFind[ncovf]=k;
                   11762:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11763:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11764:     /* }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  11765:     }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  11766:       Fixed[k]= 0;
                   11767:       Dummy[k]= 1;
1.230     brouard  11768:       nqfveff++;
1.234     brouard  11769:       modell[k].maintype= FTYPE;
                   11770:       modell[k].subtype= FQ;
                   11771:       nsq++;
1.334     brouard  11772:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11773:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11774:       ncovf++;
1.234     brouard  11775:       TvarF[ncovf]=Tvar[k];
                   11776:       TvarFind[ncovf]=k;
1.231     brouard  11777:       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  11778:       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  11779:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11780:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11781:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11782:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11783:       ncovvt++;
                   11784:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11785:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11786: 
1.227     brouard  11787:       Fixed[k]= 1;
                   11788:       Dummy[k]= 0;
1.225     brouard  11789:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11790:       modell[k].maintype= VTYPE;
                   11791:       modell[k].subtype= VD;
                   11792:       nsd++;
                   11793:       TvarsD[nsd]=Tvar[k];
                   11794:       TvarsDind[nsd]=k;
1.330     brouard  11795:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11796:       ncovv++; /* Only simple time varying variables */
                   11797:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11798:       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  11799:       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 */
                   11800:       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  11801:       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);
                   11802:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11803:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11804:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11805:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11806:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11807:       ncovvt++;
                   11808:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11809:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11810:       
1.234     brouard  11811:       Fixed[k]= 1;
                   11812:       Dummy[k]= 1;
                   11813:       nqtveff++;
                   11814:       modell[k].maintype= VTYPE;
                   11815:       modell[k].subtype= VQ;
                   11816:       ncovv++; /* Only simple time varying variables */
                   11817:       nsq++;
1.334     brouard  11818:       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) */
                   11819:       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  11820:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11821:       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  11822:       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 */
                   11823:       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  11824:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11825:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11826:       /* 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  11827:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11828:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11829:       ncova++;
                   11830:       TvarA[ncova]=Tvar[k];
                   11831:       TvarAind[ncova]=k;
1.349     brouard  11832:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11833:       /** 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  11834:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11835:        Fixed[k]= 2;
                   11836:        Dummy[k]= 2;
                   11837:        modell[k].maintype= ATYPE;
                   11838:        modell[k].subtype= APFD;
1.349     brouard  11839:        ncovta++;
                   11840:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11841:        TvarAVVAind[ncovta]=k;
1.240     brouard  11842:        /* ncoveff++; */
1.227     brouard  11843:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11844:        Fixed[k]= 2;
                   11845:        Dummy[k]= 3;
                   11846:        modell[k].maintype= ATYPE;
                   11847:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11848:        ncovta++;
                   11849:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11850:        TvarAVVAind[ncovta]=k;
1.240     brouard  11851:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11852:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11853:        Fixed[k]= 3;
                   11854:        Dummy[k]= 2;
                   11855:        modell[k].maintype= ATYPE;
                   11856:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11857:        ncovva++;
                   11858:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11859:        TvarVVAind[ncovva]=k;
                   11860:        ncovta++;
                   11861:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11862:        TvarAVVAind[ncovta]=k;
1.240     brouard  11863:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11864:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11865:        Fixed[k]= 3;
                   11866:        Dummy[k]= 3;
                   11867:        modell[k].maintype= ATYPE;
                   11868:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11869:        ncovva++;
                   11870:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11871:        TvarVVAind[ncovva]=k;
                   11872:        ncovta++;
                   11873:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11874:        TvarAVVAind[ncovta]=k;
1.240     brouard  11875:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11876:       }
1.349     brouard  11877:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11878:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11879:       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 */
                   11880:       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]]);
                   11881:        Fixed[k]= 0;
                   11882:        Dummy[k]= 0;
                   11883:        ncoveff++;
                   11884:        ncovf++;
                   11885:        /* ncovv++; */
                   11886:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11887:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11888:        /* ncovv++; */
                   11889:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11890:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11891:        modell[k].maintype= FTYPE;
                   11892:        TvarF[ncovf]=Tvar[k];
                   11893:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11894:        TvarFind[ncovf]=k;
                   11895:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11896:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11897:       }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  */
                   11898:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11899:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11900:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11901:        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 */
                   11902:        ncovvt++;
                   11903:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11904:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11905:        ncovvt++;
                   11906:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11907:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11908:        
                   11909:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11910:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11911:        
                   11912:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11913:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11914:            Fixed[k]= 1;
                   11915:            Dummy[k]= 0;
                   11916:            modell[k].maintype= FTYPE;
                   11917:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11918:            ncovf++; /* Fixed variables without age */
                   11919:            TvarF[ncovf]=Tvar[k];
                   11920:            TvarFind[ncovf]=k;
                   11921:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11922:            Fixed[k]= 0;  /* Fixed product */
                   11923:            Dummy[k]= 1;
                   11924:            modell[k].maintype= FTYPE;
                   11925:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11926:            ncovf++; /* Varying variables without age */
                   11927:            TvarF[ncovf]=Tvar[k];
                   11928:            TvarFind[ncovf]=k;
                   11929:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11930:            Fixed[k]= 1;
                   11931:            Dummy[k]= 0;
                   11932:            modell[k].maintype= VTYPE;
                   11933:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11934:            ncovv++; /* Varying variables without age */
                   11935:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11936:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11937:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11938:            Fixed[k]= 1;
                   11939:            Dummy[k]= 1;
                   11940:            modell[k].maintype= VTYPE;
                   11941:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11942:            ncovv++; /* Varying variables without age */
                   11943:            TvarV[ncovv]=Tvar[k];
                   11944:            TvarVind[ncovv]=k;
                   11945:          }
                   11946:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11947:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11948:            Fixed[k]= 0;  /*  Fixed product */
                   11949:            Dummy[k]= 1;
                   11950:            modell[k].maintype= FTYPE;
                   11951:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11952:            ncovf++; /* Fixed variables without age */
                   11953:            TvarF[ncovf]=Tvar[k];
                   11954:            TvarFind[ncovf]=k;
                   11955:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11956:            Fixed[k]= 1;
                   11957:            Dummy[k]= 1;
                   11958:            modell[k].maintype= VTYPE;
                   11959:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11960:            ncovv++; /* Varying variables without age */
                   11961:            TvarV[ncovv]=Tvar[k];
                   11962:            TvarVind[ncovv]=k;
                   11963:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11964:            Fixed[k]= 1;
                   11965:            Dummy[k]= 1;
                   11966:            modell[k].maintype= VTYPE;
                   11967:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11968:            ncovv++; /* Varying variables without age */
                   11969:            TvarV[ncovv]=Tvar[k];
                   11970:            TvarVind[ncovv]=k;
                   11971:            ncovv++; /* Varying variables without age */
                   11972:            TvarV[ncovv]=Tvar[k];
                   11973:            TvarVind[ncovv]=k;
                   11974:          }
                   11975:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11976:          if(Tvard[k1][2] <=ncovcol){
                   11977:            Fixed[k]= 1;
                   11978:            Dummy[k]= 1;
                   11979:            modell[k].maintype= VTYPE;
                   11980:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   11981:            ncovv++; /* Varying variables without age */
                   11982:            TvarV[ncovv]=Tvar[k];
                   11983:            TvarVind[ncovv]=k;
                   11984:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11985:            Fixed[k]= 1;
                   11986:            Dummy[k]= 1;
                   11987:            modell[k].maintype= VTYPE;
                   11988:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   11989:            ncovv++; /* Varying variables without age */
                   11990:            TvarV[ncovv]=Tvar[k];
                   11991:            TvarVind[ncovv]=k;
                   11992:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11993:            Fixed[k]= 1;
                   11994:            Dummy[k]= 0;
                   11995:            modell[k].maintype= VTYPE;
                   11996:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   11997:            ncovv++; /* Varying variables without age */
                   11998:            TvarV[ncovv]=Tvar[k];
                   11999:            TvarVind[ncovv]=k;
                   12000:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12001:            Fixed[k]= 1;
                   12002:            Dummy[k]= 1;
                   12003:            modell[k].maintype= VTYPE;
                   12004:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12005:            ncovv++; /* Varying variables without age */
                   12006:            TvarV[ncovv]=Tvar[k];
                   12007:            TvarVind[ncovv]=k;
                   12008:          }
                   12009:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12010:          if(Tvard[k1][2] <=ncovcol){
                   12011:            Fixed[k]= 1;
                   12012:            Dummy[k]= 1;
                   12013:            modell[k].maintype= VTYPE;
                   12014:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12015:            ncovv++; /* Varying variables without age */
                   12016:            TvarV[ncovv]=Tvar[k];
                   12017:            TvarVind[ncovv]=k;
                   12018:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12019:            Fixed[k]= 1;
                   12020:            Dummy[k]= 1;
                   12021:            modell[k].maintype= VTYPE;
                   12022:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12023:            ncovv++; /* Varying variables without age */
                   12024:            TvarV[ncovv]=Tvar[k];
                   12025:            TvarVind[ncovv]=k;
                   12026:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12027:            Fixed[k]= 1;
                   12028:            Dummy[k]= 1;
                   12029:            modell[k].maintype= VTYPE;
                   12030:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12031:            ncovv++; /* Varying variables without age */
                   12032:            TvarV[ncovv]=Tvar[k];
                   12033:            TvarVind[ncovv]=k;
                   12034:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12035:            Fixed[k]= 1;
                   12036:            Dummy[k]= 1;
                   12037:            modell[k].maintype= VTYPE;
                   12038:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12039:            ncovv++; /* Varying variables without age */
                   12040:            TvarV[ncovv]=Tvar[k];
                   12041:            TvarVind[ncovv]=k;
                   12042:          }
                   12043:        }else{
                   12044:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12045:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12046:        } /*end k1*/
                   12047:       }
                   12048:     }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  12049:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12050:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12051:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12052:       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 */
                   12053:       ncova++;
                   12054:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12055:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12056:       ncova++;
                   12057:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12058:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12059: 
1.349     brouard  12060:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12061:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12062:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12063:        ncovta++;
                   12064:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12065:        TvarAVVAind[ncovta]=k;
                   12066:        ncovta++;
                   12067:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12068:        TvarAVVAind[ncovta]=k;
                   12069:       }else{
                   12070:        ncovva++;  /* HERY  reached */
                   12071:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12072:        TvarVVAind[ncovva]=k;
                   12073:        ncovva++;
                   12074:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12075:        TvarVVAind[ncovva]=k;
                   12076:        ncovta++;
                   12077:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12078:        TvarAVVAind[ncovta]=k;
                   12079:        ncovta++;
                   12080:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12081:        TvarAVVAind[ncovta]=k;
                   12082:       }
1.339     brouard  12083:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12084:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12085:          Fixed[k]= 2;
                   12086:          Dummy[k]= 2;
1.240     brouard  12087:          modell[k].maintype= FTYPE;
                   12088:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12089:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12090:          /* TvarFind[ncova]=k; */
1.339     brouard  12091:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12092:          Fixed[k]= 2;  /* Fixed product */
                   12093:          Dummy[k]= 3;
1.240     brouard  12094:          modell[k].maintype= FTYPE;
                   12095:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12096:          /* TvarF[ncova]=Tvar[k]; */
                   12097:          /* TvarFind[ncova]=k; */
1.339     brouard  12098:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12099:          Fixed[k]= 3;
                   12100:          Dummy[k]= 2;
1.240     brouard  12101:          modell[k].maintype= VTYPE;
                   12102:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12103:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12104:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12105:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12106:          Fixed[k]= 3;
                   12107:          Dummy[k]= 3;
1.240     brouard  12108:          modell[k].maintype= VTYPE;
                   12109:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12110:          /* ncovv++; /\* Varying variables without age *\/ */
                   12111:          /* TvarV[ncovv]=Tvar[k]; */
                   12112:          /* TvarVind[ncovv]=k; */
1.240     brouard  12113:        }
1.339     brouard  12114:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12115:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12116:          Fixed[k]= 2;  /*  Fixed product */
                   12117:          Dummy[k]= 2;
1.240     brouard  12118:          modell[k].maintype= FTYPE;
                   12119:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12120:          /* ncova++; /\* Fixed variables with age *\/ */
                   12121:          /* TvarF[ncovf]=Tvar[k]; */
                   12122:          /* TvarFind[ncovf]=k; */
1.339     brouard  12123:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12124:          Fixed[k]= 2;
                   12125:          Dummy[k]= 3;
1.240     brouard  12126:          modell[k].maintype= VTYPE;
                   12127:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12128:          /* ncova++; /\* Varying variables with age *\/ */
                   12129:          /* TvarV[ncova]=Tvar[k]; */
                   12130:          /* TvarVind[ncova]=k; */
1.339     brouard  12131:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12132:          Fixed[k]= 3;
                   12133:          Dummy[k]= 2;
1.240     brouard  12134:          modell[k].maintype= VTYPE;
                   12135:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12136:          ncova++; /* Varying variables without age */
                   12137:          TvarV[ncova]=Tvar[k];
                   12138:          TvarVind[ncova]=k;
                   12139:          /* ncova++; /\* Varying variables without age *\/ */
                   12140:          /* TvarV[ncova]=Tvar[k]; */
                   12141:          /* TvarVind[ncova]=k; */
1.240     brouard  12142:        }
1.339     brouard  12143:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12144:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12145:          Fixed[k]= 2;
                   12146:          Dummy[k]= 2;
1.240     brouard  12147:          modell[k].maintype= VTYPE;
                   12148:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12149:          /* ncova++; /\* Varying variables with age *\/ */
                   12150:          /* TvarV[ncova]=Tvar[k]; */
                   12151:          /* TvarVind[ncova]=k; */
1.240     brouard  12152:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12153:          Fixed[k]= 2;
                   12154:          Dummy[k]= 3;
1.240     brouard  12155:          modell[k].maintype= VTYPE;
                   12156:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12157:          /* ncova++; /\* Varying variables with age *\/ */
                   12158:          /* TvarV[ncova]=Tvar[k]; */
                   12159:          /* TvarVind[ncova]=k; */
1.240     brouard  12160:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12161:          Fixed[k]= 3;
                   12162:          Dummy[k]= 2;
1.240     brouard  12163:          modell[k].maintype= VTYPE;
                   12164:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12165:          /* ncova++; /\* Varying variables with age *\/ */
                   12166:          /* TvarV[ncova]=Tvar[k]; */
                   12167:          /* TvarVind[ncova]=k; */
1.240     brouard  12168:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12169:          Fixed[k]= 3;
                   12170:          Dummy[k]= 3;
1.240     brouard  12171:          modell[k].maintype= VTYPE;
                   12172:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12173:          /* ncova++; /\* Varying variables with age *\/ */
                   12174:          /* TvarV[ncova]=Tvar[k]; */
                   12175:          /* TvarVind[ncova]=k; */
1.240     brouard  12176:        }
1.339     brouard  12177:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12178:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12179:          Fixed[k]= 2;
                   12180:          Dummy[k]= 2;
1.240     brouard  12181:          modell[k].maintype= VTYPE;
                   12182:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12183:          /* ncova++; /\* Varying variables with age *\/ */
                   12184:          /* TvarV[ncova]=Tvar[k]; */
                   12185:          /* TvarVind[ncova]=k; */
1.240     brouard  12186:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12187:          Fixed[k]= 2;
                   12188:          Dummy[k]= 3;
1.240     brouard  12189:          modell[k].maintype= VTYPE;
                   12190:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12191:          /* ncova++; /\* Varying variables with age *\/ */
                   12192:          /* TvarV[ncova]=Tvar[k]; */
                   12193:          /* TvarVind[ncova]=k; */
1.240     brouard  12194:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12195:          Fixed[k]= 3;
                   12196:          Dummy[k]= 2;
1.240     brouard  12197:          modell[k].maintype= VTYPE;
                   12198:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12199:          /* ncova++; /\* Varying variables with age *\/ */
                   12200:          /* TvarV[ncova]=Tvar[k]; */
                   12201:          /* TvarVind[ncova]=k; */
1.240     brouard  12202:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12203:          Fixed[k]= 3;
                   12204:          Dummy[k]= 3;
1.240     brouard  12205:          modell[k].maintype= VTYPE;
                   12206:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12207:          /* ncova++; /\* Varying variables with age *\/ */
                   12208:          /* TvarV[ncova]=Tvar[k]; */
                   12209:          /* TvarVind[ncova]=k; */
1.240     brouard  12210:        }
1.227     brouard  12211:       }else{
1.240     brouard  12212:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12213:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12214:       } /*end k1*/
1.349     brouard  12215:     } else{
1.226     brouard  12216:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12217:       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  12218:     }
1.342     brouard  12219:     /* 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]); */
                   12220:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12221:     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]);
                   12222:   }
1.349     brouard  12223:   ncovvta=ncovva;
1.227     brouard  12224:   /* Searching for doublons in the model */
                   12225:   for(k1=1; k1<= cptcovt;k1++){
                   12226:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12227:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12228:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12229:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12230:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12231:            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]);
                   12232:            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  12233:            return(1);
                   12234:          }
                   12235:        }else if (Typevar[k1] ==2){
                   12236:          k3=Tposprod[k1];
                   12237:          k4=Tposprod[k2];
                   12238:          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  12239:            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]]);
                   12240:            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  12241:            return(1);
                   12242:          }
                   12243:        }
1.227     brouard  12244:       }
                   12245:     }
1.225     brouard  12246:   }
                   12247:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12248:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12249:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12250:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12251: 
                   12252:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12253:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12254:   /*endread:*/
1.225     brouard  12255:   printf("Exiting decodemodel: ");
                   12256:   return (1);
1.136     brouard  12257: }
                   12258: 
1.169     brouard  12259: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12260: {/* Check ages at death */
1.136     brouard  12261:   int i, m;
1.218     brouard  12262:   int firstone=0;
                   12263:   
1.136     brouard  12264:   for (i=1; i<=imx; i++) {
                   12265:     for(m=2; (m<= maxwav); m++) {
                   12266:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12267:        anint[m][i]=9999;
1.216     brouard  12268:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12269:          s[m][i]=-1;
1.136     brouard  12270:       }
                   12271:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12272:        *nberr = *nberr + 1;
1.218     brouard  12273:        if(firstone == 0){
                   12274:          firstone=1;
1.260     brouard  12275:        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  12276:        }
1.262     brouard  12277:        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  12278:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12279:       }
                   12280:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12281:        (*nberr)++;
1.259     brouard  12282:        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  12283:        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  12284:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12285:       }
                   12286:     }
                   12287:   }
                   12288: 
                   12289:   for (i=1; i<=imx; i++)  {
                   12290:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12291:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12292:       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  12293:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12294:          if(agedc[i]>0){
                   12295:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12296:              agev[m][i]=agedc[i];
1.214     brouard  12297:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12298:            }else {
1.136     brouard  12299:              if ((int)andc[i]!=9999){
                   12300:                nbwarn++;
                   12301:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12302:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12303:                agev[m][i]=-1;
                   12304:              }
                   12305:            }
1.169     brouard  12306:          } /* agedc > 0 */
1.214     brouard  12307:        } /* end if */
1.136     brouard  12308:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12309:                                 years but with the precision of a month */
                   12310:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12311:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12312:            agev[m][i]=1;
                   12313:          else if(agev[m][i] < *agemin){ 
                   12314:            *agemin=agev[m][i];
                   12315:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12316:          }
                   12317:          else if(agev[m][i] >*agemax){
                   12318:            *agemax=agev[m][i];
1.156     brouard  12319:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12320:          }
                   12321:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12322:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12323:        } /* en if 9*/
1.136     brouard  12324:        else { /* =9 */
1.214     brouard  12325:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12326:          agev[m][i]=1;
                   12327:          s[m][i]=-1;
                   12328:        }
                   12329:       }
1.214     brouard  12330:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12331:        agev[m][i]=1;
1.214     brouard  12332:       else{
                   12333:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12334:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12335:        agev[m][i]=0;
                   12336:       }
                   12337:     } /* End for lastpass */
                   12338:   }
1.136     brouard  12339:     
                   12340:   for (i=1; i<=imx; i++)  {
                   12341:     for(m=firstpass; (m<=lastpass); m++){
                   12342:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12343:        (*nberr)++;
1.136     brouard  12344:        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);     
                   12345:        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);     
                   12346:        return 1;
                   12347:       }
                   12348:     }
                   12349:   }
                   12350: 
                   12351:   /*for (i=1; i<=imx; i++){
                   12352:   for (m=firstpass; (m<lastpass); m++){
                   12353:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12354: }
                   12355: 
                   12356: }*/
                   12357: 
                   12358: 
1.139     brouard  12359:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12360:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12361: 
                   12362:   return (0);
1.164     brouard  12363:  /* endread:*/
1.136     brouard  12364:     printf("Exiting calandcheckages: ");
                   12365:     return (1);
                   12366: }
                   12367: 
1.172     brouard  12368: #if defined(_MSC_VER)
                   12369: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12370: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12371: //#include "stdafx.h"
                   12372: //#include <stdio.h>
                   12373: //#include <tchar.h>
                   12374: //#include <windows.h>
                   12375: //#include <iostream>
                   12376: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12377: 
                   12378: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12379: 
                   12380: BOOL IsWow64()
                   12381: {
                   12382:        BOOL bIsWow64 = FALSE;
                   12383: 
                   12384:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12385:        //  (HANDLE, PBOOL);
                   12386: 
                   12387:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12388: 
                   12389:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12390:        const char funcName[] = "IsWow64Process";
                   12391:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12392:                GetProcAddress(module, funcName);
                   12393: 
                   12394:        if (NULL != fnIsWow64Process)
                   12395:        {
                   12396:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12397:                        &bIsWow64))
                   12398:                        //throw std::exception("Unknown error");
                   12399:                        printf("Unknown error\n");
                   12400:        }
                   12401:        return bIsWow64 != FALSE;
                   12402: }
                   12403: #endif
1.177     brouard  12404: 
1.191     brouard  12405: void syscompilerinfo(int logged)
1.292     brouard  12406: {
                   12407: #include <stdint.h>
                   12408: 
                   12409:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12410:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12411:    /* /GS /W3 /Gy
                   12412:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12413:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12414:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12415:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12416:    */ 
                   12417:    /* 64 bits */
1.185     brouard  12418:    /*
                   12419:      /GS /W3 /Gy
                   12420:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12421:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12422:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12423:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12424:    /* Optimization are useless and O3 is slower than O2 */
                   12425:    /*
                   12426:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12427:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12428:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12429:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12430:    */
1.186     brouard  12431:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12432:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12433:       /PDB:"visual studio
                   12434:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12435:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12436:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12437:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12438:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12439:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12440:       uiAccess='false'"
                   12441:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12442:       /NOLOGO /TLBID:1
                   12443:    */
1.292     brouard  12444: 
                   12445: 
1.177     brouard  12446: #if defined __INTEL_COMPILER
1.178     brouard  12447: #if defined(__GNUC__)
                   12448:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12449: #endif
1.177     brouard  12450: #elif defined(__GNUC__) 
1.179     brouard  12451: #ifndef  __APPLE__
1.174     brouard  12452: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12453: #endif
1.177     brouard  12454:    struct utsname sysInfo;
1.178     brouard  12455:    int cross = CROSS;
                   12456:    if (cross){
                   12457:           printf("Cross-");
1.191     brouard  12458:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12459:    }
1.174     brouard  12460: #endif
                   12461: 
1.191     brouard  12462:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12463: #if defined(__clang__)
1.191     brouard  12464:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12465: #endif
                   12466: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12467:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12468: #endif
                   12469: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12470:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12471: #endif
                   12472: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12473:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12474: #endif
                   12475: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12476:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12477: #endif
                   12478: #if defined(_MSC_VER)
1.191     brouard  12479:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12480: #endif
                   12481: #if defined(__PGI)
1.191     brouard  12482:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12483: #endif
                   12484: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12485:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12486: #endif
1.191     brouard  12487:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12488:    
1.167     brouard  12489: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12490: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12491:     // Windows (x64 and x86)
1.191     brouard  12492:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12493: #elif __unix__ // all unices, not all compilers
                   12494:     // Unix
1.191     brouard  12495:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12496: #elif __linux__
                   12497:     // linux
1.191     brouard  12498:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12499: #elif __APPLE__
1.174     brouard  12500:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12501:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12502: #endif
                   12503: 
                   12504: /*  __MINGW32__          */
                   12505: /*  __CYGWIN__  */
                   12506: /* __MINGW64__  */
                   12507: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12508: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12509: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12510: /* _WIN64  // Defined for applications for Win64. */
                   12511: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12512: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12513: 
1.167     brouard  12514: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12515:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12516: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12517:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12518: #else
1.191     brouard  12519:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12520: #endif
                   12521: 
1.169     brouard  12522: #if defined(__GNUC__)
                   12523: # if defined(__GNUC_PATCHLEVEL__)
                   12524: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12525:                             + __GNUC_MINOR__ * 100 \
                   12526:                             + __GNUC_PATCHLEVEL__)
                   12527: # else
                   12528: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12529:                             + __GNUC_MINOR__ * 100)
                   12530: # endif
1.174     brouard  12531:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12532:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12533: 
                   12534:    if (uname(&sysInfo) != -1) {
                   12535:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12536:         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  12537:    }
                   12538:    else
                   12539:       perror("uname() error");
1.179     brouard  12540:    //#ifndef __INTEL_COMPILER 
                   12541: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12542:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12543:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12544: #endif
1.169     brouard  12545: #endif
1.172     brouard  12546: 
1.286     brouard  12547:    //   void main ()
1.172     brouard  12548:    //   {
1.169     brouard  12549: #if defined(_MSC_VER)
1.174     brouard  12550:    if (IsWow64()){
1.191     brouard  12551:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12552:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12553:    }
                   12554:    else{
1.191     brouard  12555:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12556:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12557:    }
1.172     brouard  12558:    //     printf("\nPress Enter to continue...");
                   12559:    //     getchar();
                   12560:    //   }
                   12561: 
1.169     brouard  12562: #endif
                   12563:    
1.167     brouard  12564: 
1.219     brouard  12565: }
1.136     brouard  12566: 
1.219     brouard  12567: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12568:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12569:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12570:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12571:   /* double ftolpl = 1.e-10; */
1.180     brouard  12572:   double age, agebase, agelim;
1.203     brouard  12573:   double tot;
1.180     brouard  12574: 
1.202     brouard  12575:   strcpy(filerespl,"PL_");
                   12576:   strcat(filerespl,fileresu);
                   12577:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12578:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12579:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12580:   }
1.288     brouard  12581:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12582:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12583:   pstamp(ficrespl);
1.288     brouard  12584:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12585:   fprintf(ficrespl,"#Age ");
                   12586:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12587:   fprintf(ficrespl,"\n");
1.180     brouard  12588:   
1.219     brouard  12589:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12590: 
1.219     brouard  12591:   agebase=ageminpar;
                   12592:   agelim=agemaxpar;
1.180     brouard  12593: 
1.227     brouard  12594:   /* i1=pow(2,ncoveff); */
1.234     brouard  12595:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12596:   if (cptcovn < 1){i1=1;}
1.180     brouard  12597: 
1.337     brouard  12598:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12599:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12600:       k=TKresult[nres];
1.338     brouard  12601:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12602:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12603:       /*       continue; */
1.235     brouard  12604: 
1.238     brouard  12605:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12606:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12607:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12608:       /* k=k+1; */
                   12609:       /* to clean */
1.332     brouard  12610:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12611:       fprintf(ficrespl,"#******");
                   12612:       printf("#******");
                   12613:       fprintf(ficlog,"#******");
1.337     brouard  12614:       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  12615:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12616:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12617:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12618:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12619:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12620:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12621:       }
                   12622:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12623:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12624:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12625:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12626:       /* } */
1.238     brouard  12627:       fprintf(ficrespl,"******\n");
                   12628:       printf("******\n");
                   12629:       fprintf(ficlog,"******\n");
                   12630:       if(invalidvarcomb[k]){
                   12631:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12632:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12633:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12634:        continue;
                   12635:       }
1.219     brouard  12636: 
1.238     brouard  12637:       fprintf(ficrespl,"#Age ");
1.337     brouard  12638:       /* for(j=1;j<=cptcoveff;j++) { */
                   12639:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12640:       /* } */
                   12641:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12642:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12643:       }
                   12644:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12645:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12646:     
1.238     brouard  12647:       for (age=agebase; age<=agelim; age++){
                   12648:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12649:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12650:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12651:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12652:        /* for(j=1;j<=cptcoveff;j++) */
                   12653:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12654:        for(j=1;j<=cptcovs;j++)
                   12655:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12656:        tot=0.;
                   12657:        for(i=1; i<=nlstate;i++){
                   12658:          tot +=  prlim[i][i];
                   12659:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12660:        }
                   12661:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12662:       } /* Age */
                   12663:       /* was end of cptcod */
1.337     brouard  12664:     } /* nres */
                   12665:   /* } /\* for each combination *\/ */
1.219     brouard  12666:   return 0;
1.180     brouard  12667: }
                   12668: 
1.218     brouard  12669: 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  12670:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12671:        
                   12672:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12673:    * at any age between ageminpar and agemaxpar
                   12674:         */
1.235     brouard  12675:   int i, j, k, i1, nres=0 ;
1.217     brouard  12676:   /* double ftolpl = 1.e-10; */
                   12677:   double age, agebase, agelim;
                   12678:   double tot;
1.218     brouard  12679:   /* double ***mobaverage; */
                   12680:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12681: 
                   12682:   strcpy(fileresplb,"PLB_");
                   12683:   strcat(fileresplb,fileresu);
                   12684:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12685:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12686:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12687:   }
1.288     brouard  12688:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12689:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12690:   pstamp(ficresplb);
1.288     brouard  12691:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12692:   fprintf(ficresplb,"#Age ");
                   12693:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12694:   fprintf(ficresplb,"\n");
                   12695:   
1.218     brouard  12696:   
                   12697:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12698:   
                   12699:   agebase=ageminpar;
                   12700:   agelim=agemaxpar;
                   12701:   
                   12702:   
1.227     brouard  12703:   i1=pow(2,cptcoveff);
1.218     brouard  12704:   if (cptcovn < 1){i1=1;}
1.227     brouard  12705:   
1.238     brouard  12706:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12707:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12708:       k=TKresult[nres];
                   12709:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12710:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12711:      /*        continue; */
                   12712:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12713:       fprintf(ficresplb,"#******");
                   12714:       printf("#******");
                   12715:       fprintf(ficlog,"#******");
1.338     brouard  12716:       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) */
                   12717:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12718:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12719:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12720:       }
1.338     brouard  12721:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12722:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12723:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12724:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12725:       /* } */
                   12726:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12727:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12728:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12729:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12730:       /* } */
1.238     brouard  12731:       fprintf(ficresplb,"******\n");
                   12732:       printf("******\n");
                   12733:       fprintf(ficlog,"******\n");
                   12734:       if(invalidvarcomb[k]){
                   12735:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12736:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12737:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12738:        continue;
                   12739:       }
1.218     brouard  12740:     
1.238     brouard  12741:       fprintf(ficresplb,"#Age ");
1.338     brouard  12742:       for(j=1;j<=cptcovs;j++) {
                   12743:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12744:       }
                   12745:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12746:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12747:     
                   12748:     
1.238     brouard  12749:       for (age=agebase; age<=agelim; age++){
                   12750:        /* for (age=agebase; age<=agebase; age++){ */
                   12751:        if(mobilavproj > 0){
                   12752:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12753:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12754:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12755:        }else if (mobilavproj == 0){
                   12756:          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);
                   12757:          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);
                   12758:          exit(1);
                   12759:        }else{
                   12760:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12761:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12762:          /* printf("TOTOT\n"); */
                   12763:           /* exit(1); */
1.238     brouard  12764:        }
                   12765:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12766:        for(j=1;j<=cptcovs;j++)
                   12767:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12768:        tot=0.;
                   12769:        for(i=1; i<=nlstate;i++){
                   12770:          tot +=  bprlim[i][i];
                   12771:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12772:        }
                   12773:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12774:       } /* Age */
                   12775:       /* was end of cptcod */
1.255     brouard  12776:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12777:     /* } /\* end of any combination *\/ */
1.238     brouard  12778:   } /* end of nres */  
1.218     brouard  12779:   /* hBijx(p, bage, fage); */
                   12780:   /* fclose(ficrespijb); */
                   12781:   
                   12782:   return 0;
1.217     brouard  12783: }
1.218     brouard  12784:  
1.180     brouard  12785: int hPijx(double *p, int bage, int fage){
                   12786:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12787:   /* to be optimized with precov */
1.180     brouard  12788:   int stepsize;
                   12789:   int agelim;
                   12790:   int hstepm;
                   12791:   int nhstepm;
1.235     brouard  12792:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12793: 
                   12794:   double agedeb;
                   12795:   double ***p3mat;
                   12796: 
1.337     brouard  12797:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12798:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12799:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12800:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12801:   }
                   12802:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12803:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12804:   
                   12805:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12806:   /*if (stepm<=24) stepsize=2;*/
                   12807:   
                   12808:   agelim=AGESUP;
                   12809:   hstepm=stepsize*YEARM; /* Every year of age */
                   12810:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12811:   
                   12812:   /* hstepm=1;   aff par mois*/
                   12813:   pstamp(ficrespij);
                   12814:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12815:   i1= pow(2,cptcoveff);
                   12816:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12817:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12818:   /*   k=k+1;  */
                   12819:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12820:     k=TKresult[nres];
1.338     brouard  12821:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12822:     /* for(k=1; k<=i1;k++){ */
                   12823:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12824:     /*         continue; */
                   12825:     fprintf(ficrespij,"\n#****** ");
                   12826:     for(j=1;j<=cptcovs;j++){
                   12827:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12828:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12829:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12830:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12831:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12832:     }
                   12833:     fprintf(ficrespij,"******\n");
                   12834:     
                   12835:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12836:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12837:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12838:       
                   12839:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12840:       
                   12841:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12842:       oldm=oldms;savm=savms;
                   12843:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12844:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12845:       for(i=1; i<=nlstate;i++)
                   12846:        for(j=1; j<=nlstate+ndeath;j++)
                   12847:          fprintf(ficrespij," %1d-%1d",i,j);
                   12848:       fprintf(ficrespij,"\n");
                   12849:       for (h=0; h<=nhstepm; h++){
                   12850:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12851:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12852:        for(i=1; i<=nlstate;i++)
                   12853:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12854:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12855:        fprintf(ficrespij,"\n");
                   12856:       }
1.337     brouard  12857:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12858:       fprintf(ficrespij,"\n");
1.180     brouard  12859:     }
1.337     brouard  12860:   }
                   12861:   /*}*/
                   12862:   return 0;
1.180     brouard  12863: }
1.218     brouard  12864:  
                   12865:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12866:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12867:     /* To be optimized with precov */
1.217     brouard  12868:   int stepsize;
1.218     brouard  12869:   /* int agelim; */
                   12870:        int ageminl;
1.217     brouard  12871:   int hstepm;
                   12872:   int nhstepm;
1.238     brouard  12873:   int h, i, i1, j, k, nres;
1.218     brouard  12874:        
1.217     brouard  12875:   double agedeb;
                   12876:   double ***p3mat;
1.218     brouard  12877:        
                   12878:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12879:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12880:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12881:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12882:   }
                   12883:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12884:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12885:   
                   12886:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12887:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12888:   
1.218     brouard  12889:   /* agelim=AGESUP; */
1.289     brouard  12890:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12891:   hstepm=stepsize*YEARM; /* Every year of age */
                   12892:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12893:   
                   12894:   /* hstepm=1;   aff par mois*/
                   12895:   pstamp(ficrespijb);
1.255     brouard  12896:   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  12897:   i1= pow(2,cptcoveff);
1.218     brouard  12898:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12899:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12900:   /*   k=k+1;  */
1.238     brouard  12901:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12902:     k=TKresult[nres];
1.338     brouard  12903:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12904:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12905:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12906:     /*         continue; */
                   12907:     fprintf(ficrespijb,"\n#****** ");
                   12908:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12909:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12910:       /* for(j=1;j<=cptcoveff;j++) */
                   12911:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12912:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12913:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12914:     }
                   12915:     fprintf(ficrespijb,"******\n");
                   12916:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12917:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12918:       continue;
                   12919:     }
                   12920:     
                   12921:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12922:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12923:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12924:       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 */
                   12925:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12926:       
                   12927:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12928:       
                   12929:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12930:       /* and memory limitations if stepm is small */
                   12931:       
                   12932:       /* oldm=oldms;savm=savms; */
                   12933:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12934:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12935:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12936:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12937:       for(i=1; i<=nlstate;i++)
                   12938:        for(j=1; j<=nlstate+ndeath;j++)
                   12939:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12940:       fprintf(ficrespijb,"\n");
                   12941:       for (h=0; h<=nhstepm; h++){
                   12942:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12943:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12944:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12945:        for(i=1; i<=nlstate;i++)
                   12946:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12947:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12948:        fprintf(ficrespijb,"\n");
1.337     brouard  12949:       }
                   12950:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12951:       fprintf(ficrespijb,"\n");
                   12952:     } /* end age deb */
                   12953:     /* } /\* end combination *\/ */
1.238     brouard  12954:   } /* end nres */
1.218     brouard  12955:   return 0;
                   12956:  } /*  hBijx */
1.217     brouard  12957: 
1.180     brouard  12958: 
1.136     brouard  12959: /***********************************************/
                   12960: /**************** Main Program *****************/
                   12961: /***********************************************/
                   12962: 
                   12963: int main(int argc, char *argv[])
                   12964: {
                   12965: #ifdef GSL
                   12966:   const gsl_multimin_fminimizer_type *T;
                   12967:   size_t iteri = 0, it;
                   12968:   int rval = GSL_CONTINUE;
                   12969:   int status = GSL_SUCCESS;
                   12970:   double ssval;
                   12971: #endif
                   12972:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12973:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12974:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12975:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12976:   int jj, ll, li, lj, lk;
1.136     brouard  12977:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12978:   int num_filled;
1.136     brouard  12979:   int itimes;
                   12980:   int NDIM=2;
                   12981:   int vpopbased=0;
1.235     brouard  12982:   int nres=0;
1.258     brouard  12983:   int endishere=0;
1.277     brouard  12984:   int noffset=0;
1.274     brouard  12985:   int ncurrv=0; /* Temporary variable */
                   12986:   
1.164     brouard  12987:   char ca[32], cb[32];
1.136     brouard  12988:   /*  FILE *fichtm; *//* Html File */
                   12989:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12990:   struct stat info;
1.191     brouard  12991:   double agedeb=0.;
1.194     brouard  12992: 
                   12993:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12994:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12995: 
1.165     brouard  12996:   double fret;
1.191     brouard  12997:   double dum=0.; /* Dummy variable */
1.136     brouard  12998:   double ***p3mat;
1.218     brouard  12999:   /* double ***mobaverage; */
1.319     brouard  13000:   double wald;
1.164     brouard  13001: 
1.351   ! brouard  13002:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13003:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13004: 
1.234     brouard  13005:   char  modeltemp[MAXLINE];
1.332     brouard  13006:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13007:   
1.136     brouard  13008:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13009:   char *tok, *val; /* pathtot */
1.334     brouard  13010:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13011:   int c,  h , cpt, c2;
1.191     brouard  13012:   int jl=0;
                   13013:   int i1, j1, jk, stepsize=0;
1.194     brouard  13014:   int count=0;
                   13015: 
1.164     brouard  13016:   int *tab; 
1.136     brouard  13017:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13018:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13019:   /* double anprojf, mprojf, jprojf; */
                   13020:   /* double jintmean,mintmean,aintmean;   */
                   13021:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13022:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13023:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13024:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13025:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13026:   int mobilav=0,popforecast=0;
1.191     brouard  13027:   int hstepm=0, nhstepm=0;
1.136     brouard  13028:   int agemortsup;
                   13029:   float  sumlpop=0.;
                   13030:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13031:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13032: 
1.191     brouard  13033:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13034:   double ftolpl=FTOL;
                   13035:   double **prlim;
1.217     brouard  13036:   double **bprlim;
1.317     brouard  13037:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13038:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13039:   double ***paramstart; /* Matrix of starting parameter values */
                   13040:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13041:   double **matcov; /* Matrix of covariance */
1.203     brouard  13042:   double **hess; /* Hessian matrix */
1.136     brouard  13043:   double ***delti3; /* Scale */
                   13044:   double *delti; /* Scale */
                   13045:   double ***eij, ***vareij;
                   13046:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13047: 
1.136     brouard  13048:   double *epj, vepp;
1.164     brouard  13049: 
1.273     brouard  13050:   double dateprev1, dateprev2;
1.296     brouard  13051:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13052:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13053: 
1.217     brouard  13054: 
1.136     brouard  13055:   double **ximort;
1.145     brouard  13056:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13057:   int *dcwave;
                   13058: 
1.164     brouard  13059:   char z[1]="c";
1.136     brouard  13060: 
                   13061:   /*char  *strt;*/
                   13062:   char strtend[80];
1.126     brouard  13063: 
1.164     brouard  13064: 
1.126     brouard  13065: /*   setlocale (LC_ALL, ""); */
                   13066: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13067: /*   textdomain (PACKAGE); */
                   13068: /*   setlocale (LC_CTYPE, ""); */
                   13069: /*   setlocale (LC_MESSAGES, ""); */
                   13070: 
                   13071:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13072:   rstart_time = time(NULL);  
                   13073:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13074:   start_time = *localtime(&rstart_time);
1.126     brouard  13075:   curr_time=start_time;
1.157     brouard  13076:   /*tml = *localtime(&start_time.tm_sec);*/
                   13077:   /* strcpy(strstart,asctime(&tml)); */
                   13078:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13079: 
                   13080: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13081: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13082: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13083: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13084: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13085: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13086: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13087: /*   strt=asctime(&tmg); */
                   13088: /*   printf("Time(after) =%s",strstart);  */
                   13089: /*  (void) time (&time_value);
                   13090: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13091: *  tm = *localtime(&time_value);
                   13092: *  strstart=asctime(&tm);
                   13093: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13094: */
                   13095: 
                   13096:   nberr=0; /* Number of errors and warnings */
                   13097:   nbwarn=0;
1.184     brouard  13098: #ifdef WIN32
                   13099:   _getcwd(pathcd, size);
                   13100: #else
1.126     brouard  13101:   getcwd(pathcd, size);
1.184     brouard  13102: #endif
1.191     brouard  13103:   syscompilerinfo(0);
1.196     brouard  13104:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13105:   if(argc <=1){
                   13106:     printf("\nEnter the parameter file name: ");
1.205     brouard  13107:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13108:       printf("ERROR Empty parameter file name\n");
                   13109:       goto end;
                   13110:     }
1.126     brouard  13111:     i=strlen(pathr);
                   13112:     if(pathr[i-1]=='\n')
                   13113:       pathr[i-1]='\0';
1.156     brouard  13114:     i=strlen(pathr);
1.205     brouard  13115:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13116:       pathr[i-1]='\0';
1.205     brouard  13117:     }
                   13118:     i=strlen(pathr);
                   13119:     if( i==0 ){
                   13120:       printf("ERROR Empty parameter file name\n");
                   13121:       goto end;
                   13122:     }
                   13123:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13124:       printf("Pathr |%s|\n",pathr);
                   13125:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13126:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13127:       strcpy (pathtot, val);
                   13128:       if(pathr[0] == '\0') break; /* Dirty */
                   13129:     }
                   13130:   }
1.281     brouard  13131:   else if (argc<=2){
                   13132:     strcpy(pathtot,argv[1]);
                   13133:   }
1.126     brouard  13134:   else{
                   13135:     strcpy(pathtot,argv[1]);
1.281     brouard  13136:     strcpy(z,argv[2]);
                   13137:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13138:   }
                   13139:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13140:   /*cygwin_split_path(pathtot,path,optionfile);
                   13141:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13142:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13143: 
                   13144:   /* Split argv[0], imach program to get pathimach */
                   13145:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13146:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13147:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13148:  /*   strcpy(pathimach,argv[0]); */
                   13149:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13150:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13151:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13152: #ifdef WIN32
                   13153:   _chdir(path); /* Can be a relative path */
                   13154:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13155: #else
1.126     brouard  13156:   chdir(path); /* Can be a relative path */
1.184     brouard  13157:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13158: #endif
                   13159:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13160:   strcpy(command,"mkdir ");
                   13161:   strcat(command,optionfilefiname);
                   13162:   if((outcmd=system(command)) != 0){
1.169     brouard  13163:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13164:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13165:     /* fclose(ficlog); */
                   13166: /*     exit(1); */
                   13167:   }
                   13168: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13169: /*     perror("mkdir"); */
                   13170: /*   } */
                   13171: 
                   13172:   /*-------- arguments in the command line --------*/
                   13173: 
1.186     brouard  13174:   /* Main Log file */
1.126     brouard  13175:   strcat(filelog, optionfilefiname);
                   13176:   strcat(filelog,".log");    /* */
                   13177:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13178:     printf("Problem with logfile %s\n",filelog);
                   13179:     goto end;
                   13180:   }
                   13181:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13182:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13183:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13184:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13185:  path=%s \n\
                   13186:  optionfile=%s\n\
                   13187:  optionfilext=%s\n\
1.156     brouard  13188:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13189: 
1.197     brouard  13190:   syscompilerinfo(1);
1.167     brouard  13191: 
1.126     brouard  13192:   printf("Local time (at start):%s",strstart);
                   13193:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13194:   fflush(ficlog);
                   13195: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13196: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13197: 
                   13198:   /* */
                   13199:   strcpy(fileres,"r");
                   13200:   strcat(fileres, optionfilefiname);
1.201     brouard  13201:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13202:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13203:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13204: 
1.186     brouard  13205:   /* Main ---------arguments file --------*/
1.126     brouard  13206: 
                   13207:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13208:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13209:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13210:     fflush(ficlog);
1.149     brouard  13211:     /* goto end; */
                   13212:     exit(70); 
1.126     brouard  13213:   }
                   13214: 
                   13215:   strcpy(filereso,"o");
1.201     brouard  13216:   strcat(filereso,fileresu);
1.126     brouard  13217:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13218:     printf("Problem with Output resultfile: %s\n", filereso);
                   13219:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13220:     fflush(ficlog);
                   13221:     goto end;
                   13222:   }
1.278     brouard  13223:       /*-------- Rewriting parameter file ----------*/
                   13224:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13225:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13226:   strcat(rfileres,".");    /* */
                   13227:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13228:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13229:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13230:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13231:     fflush(ficlog);
                   13232:     goto end;
                   13233:   }
                   13234:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13235: 
1.278     brouard  13236:                                      
1.126     brouard  13237:   /* Reads comments: lines beginning with '#' */
                   13238:   numlinepar=0;
1.277     brouard  13239:   /* Is it a BOM UTF-8 Windows file? */
                   13240:   /* First parameter line */
1.197     brouard  13241:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13242:     noffset=0;
                   13243:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13244:     {
                   13245:       noffset=noffset+3;
                   13246:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13247:     }
1.302     brouard  13248: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13249:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13250:     {
                   13251:       noffset=noffset+2;
                   13252:       printf("# File is an UTF16BE BOM file\n");
                   13253:     }
                   13254:     else if( line[0] == 0 && line[1] == 0)
                   13255:     {
                   13256:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13257:        noffset=noffset+4;
                   13258:        printf("# File is an UTF16BE BOM file\n");
                   13259:       }
                   13260:     } else{
                   13261:       ;/*printf(" Not a BOM file\n");*/
                   13262:     }
                   13263:   
1.197     brouard  13264:     /* If line starts with a # it is a comment */
1.277     brouard  13265:     if (line[noffset] == '#') {
1.197     brouard  13266:       numlinepar++;
                   13267:       fputs(line,stdout);
                   13268:       fputs(line,ficparo);
1.278     brouard  13269:       fputs(line,ficres);
1.197     brouard  13270:       fputs(line,ficlog);
                   13271:       continue;
                   13272:     }else
                   13273:       break;
                   13274:   }
                   13275:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13276:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13277:     if (num_filled != 5) {
                   13278:       printf("Should be 5 parameters\n");
1.283     brouard  13279:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13280:     }
1.126     brouard  13281:     numlinepar++;
1.197     brouard  13282:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13283:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13284:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13285:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13286:   }
                   13287:   /* Second parameter line */
                   13288:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13289:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13290:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13291:     if (line[0] == '#') {
                   13292:       numlinepar++;
1.283     brouard  13293:       printf("%s",line);
                   13294:       fprintf(ficres,"%s",line);
                   13295:       fprintf(ficparo,"%s",line);
                   13296:       fprintf(ficlog,"%s",line);
1.197     brouard  13297:       continue;
                   13298:     }else
                   13299:       break;
                   13300:   }
1.223     brouard  13301:   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", \
                   13302:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13303:     if (num_filled != 11) {
                   13304:       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  13305:       printf("but line=%s\n",line);
1.283     brouard  13306:       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");
                   13307:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13308:     }
1.286     brouard  13309:     if( lastpass > maxwav){
                   13310:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13311:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13312:       fflush(ficlog);
                   13313:       goto end;
                   13314:     }
                   13315:       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  13316:     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  13317:     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  13318:     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  13319:   }
1.203     brouard  13320:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13321:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13322:   /* Third parameter line */
                   13323:   while(fgets(line, MAXLINE, ficpar)) {
                   13324:     /* If line starts with a # it is a comment */
                   13325:     if (line[0] == '#') {
                   13326:       numlinepar++;
1.283     brouard  13327:       printf("%s",line);
                   13328:       fprintf(ficres,"%s",line);
                   13329:       fprintf(ficparo,"%s",line);
                   13330:       fprintf(ficlog,"%s",line);
1.197     brouard  13331:       continue;
                   13332:     }else
                   13333:       break;
                   13334:   }
1.351   ! brouard  13335:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
        !          13336:     if (num_filled != 1){
        !          13337:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
        !          13338:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
        !          13339:       model[0]='\0';
        !          13340:       goto end;
        !          13341:     }else{
        !          13342:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
        !          13343:       strcpy(line, linetmp);
        !          13344:     }
        !          13345:   }
        !          13346:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13347:     if (num_filled != 1){
1.302     brouard  13348:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13349:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13350:       model[0]='\0';
                   13351:       goto end;
                   13352:     }
                   13353:     else{
                   13354:       if (model[0]=='+'){
                   13355:        for(i=1; i<=strlen(model);i++)
                   13356:          modeltemp[i-1]=model[i];
1.201     brouard  13357:        strcpy(model,modeltemp); 
1.197     brouard  13358:       }
                   13359:     }
1.338     brouard  13360:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13361:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13362:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13363:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13364:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13365:   }
                   13366:   /* 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); */
                   13367:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13368:   /* 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  13369:   /* 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); */
                   13370:   /* 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  13371:   fflush(ficlog);
1.190     brouard  13372:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13373:   if(model[0]=='#'){
1.279     brouard  13374:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13375:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13376:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13377:     if(mle != -1){
1.279     brouard  13378:       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  13379:       exit(1);
                   13380:     }
                   13381:   }
1.126     brouard  13382:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13383:     ungetc(c,ficpar);
                   13384:     fgets(line, MAXLINE, ficpar);
                   13385:     numlinepar++;
1.195     brouard  13386:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13387:       z[0]=line[1];
1.342     brouard  13388:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13389:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13390:     }
                   13391:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13392:     fputs(line, stdout);
                   13393:     //puts(line);
1.126     brouard  13394:     fputs(line,ficparo);
                   13395:     fputs(line,ficlog);
                   13396:   }
                   13397:   ungetc(c,ficpar);
                   13398: 
                   13399:    
1.290     brouard  13400:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13401:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13402:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13403:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13404:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13405:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13406:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13407:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13408:   */
                   13409:   if (strlen(model)>1) 
1.187     brouard  13410:     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  13411:   else
1.187     brouard  13412:     ncovmodel=2; /* Constant and age */
1.133     brouard  13413:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13414:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13415:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13416:     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);
                   13417:     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);
                   13418:     fflush(stdout);
                   13419:     fclose (ficlog);
                   13420:     goto end;
                   13421:   }
1.126     brouard  13422:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13423:   delti=delti3[1][1];
                   13424:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13425:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13426: /* We could also provide initial parameters values giving by simple logistic regression 
                   13427:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13428:       /* for(i=1;i<nlstate;i++){ */
                   13429:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13430:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13431:       /* } */
1.126     brouard  13432:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13433:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13434:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13435:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13436:     fclose (ficparo);
                   13437:     fclose (ficlog);
                   13438:     goto end;
                   13439:     exit(0);
1.220     brouard  13440:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13441:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13442:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13443:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13444:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13445:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13446:     hess=matrix(1,npar,1,npar);
1.220     brouard  13447:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13448:     /* Read guessed parameters */
1.126     brouard  13449:     /* Reads comments: lines beginning with '#' */
                   13450:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13451:       ungetc(c,ficpar);
                   13452:       fgets(line, MAXLINE, ficpar);
                   13453:       numlinepar++;
1.141     brouard  13454:       fputs(line,stdout);
1.126     brouard  13455:       fputs(line,ficparo);
                   13456:       fputs(line,ficlog);
                   13457:     }
                   13458:     ungetc(c,ficpar);
                   13459:     
                   13460:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13461:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13462:     for(i=1; i <=nlstate; i++){
1.234     brouard  13463:       j=0;
1.126     brouard  13464:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13465:        if(jj==i) continue;
                   13466:        j++;
1.292     brouard  13467:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13468:          ungetc(c,ficpar);
                   13469:          fgets(line, MAXLINE, ficpar);
                   13470:          numlinepar++;
                   13471:          fputs(line,stdout);
                   13472:          fputs(line,ficparo);
                   13473:          fputs(line,ficlog);
                   13474:        }
                   13475:        ungetc(c,ficpar);
1.234     brouard  13476:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13477:        if ((i1 != i) || (j1 != jj)){
                   13478:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13479: It might be a problem of design; if ncovcol and the model are correct\n \
                   13480: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13481:          exit(1);
                   13482:        }
                   13483:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13484:        if(mle==1)
                   13485:          printf("%1d%1d",i,jj);
                   13486:        fprintf(ficlog,"%1d%1d",i,jj);
                   13487:        for(k=1; k<=ncovmodel;k++){
                   13488:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13489:          if(mle==1){
                   13490:            printf(" %lf",param[i][j][k]);
                   13491:            fprintf(ficlog," %lf",param[i][j][k]);
                   13492:          }
                   13493:          else
                   13494:            fprintf(ficlog," %lf",param[i][j][k]);
                   13495:          fprintf(ficparo," %lf",param[i][j][k]);
                   13496:        }
                   13497:        fscanf(ficpar,"\n");
                   13498:        numlinepar++;
                   13499:        if(mle==1)
                   13500:          printf("\n");
                   13501:        fprintf(ficlog,"\n");
                   13502:        fprintf(ficparo,"\n");
1.126     brouard  13503:       }
                   13504:     }  
                   13505:     fflush(ficlog);
1.234     brouard  13506:     
1.251     brouard  13507:     /* Reads parameters values */
1.126     brouard  13508:     p=param[1][1];
1.251     brouard  13509:     pstart=paramstart[1][1];
1.126     brouard  13510:     
                   13511:     /* Reads comments: lines beginning with '#' */
                   13512:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13513:       ungetc(c,ficpar);
                   13514:       fgets(line, MAXLINE, ficpar);
                   13515:       numlinepar++;
1.141     brouard  13516:       fputs(line,stdout);
1.126     brouard  13517:       fputs(line,ficparo);
                   13518:       fputs(line,ficlog);
                   13519:     }
                   13520:     ungetc(c,ficpar);
                   13521: 
                   13522:     for(i=1; i <=nlstate; i++){
                   13523:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13524:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13525:        if ( (i1-i) * (j1-j) != 0){
                   13526:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13527:          exit(1);
                   13528:        }
                   13529:        printf("%1d%1d",i,j);
                   13530:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13531:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13532:        for(k=1; k<=ncovmodel;k++){
                   13533:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13534:          printf(" %le",delti3[i][j][k]);
                   13535:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13536:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13537:        }
                   13538:        fscanf(ficpar,"\n");
                   13539:        numlinepar++;
                   13540:        printf("\n");
                   13541:        fprintf(ficparo,"\n");
                   13542:        fprintf(ficlog,"\n");
1.126     brouard  13543:       }
                   13544:     }
                   13545:     fflush(ficlog);
1.234     brouard  13546:     
1.145     brouard  13547:     /* Reads covariance matrix */
1.126     brouard  13548:     delti=delti3[1][1];
1.220     brouard  13549:                
                   13550:                
1.126     brouard  13551:     /* 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  13552:                
1.126     brouard  13553:     /* Reads comments: lines beginning with '#' */
                   13554:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13555:       ungetc(c,ficpar);
                   13556:       fgets(line, MAXLINE, ficpar);
                   13557:       numlinepar++;
1.141     brouard  13558:       fputs(line,stdout);
1.126     brouard  13559:       fputs(line,ficparo);
                   13560:       fputs(line,ficlog);
                   13561:     }
                   13562:     ungetc(c,ficpar);
1.220     brouard  13563:                
1.126     brouard  13564:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13565:     hess=matrix(1,npar,1,npar);
1.131     brouard  13566:     for(i=1; i <=npar; i++)
                   13567:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13568:                
1.194     brouard  13569:     /* Scans npar lines */
1.126     brouard  13570:     for(i=1; i <=npar; i++){
1.226     brouard  13571:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13572:       if(count != 3){
1.226     brouard  13573:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13574: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13575: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13576:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13577: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13578: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13579:        exit(1);
1.220     brouard  13580:       }else{
1.226     brouard  13581:        if(mle==1)
                   13582:          printf("%1d%1d%d",i1,j1,jk);
                   13583:       }
                   13584:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13585:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13586:       for(j=1; j <=i; j++){
1.226     brouard  13587:        fscanf(ficpar," %le",&matcov[i][j]);
                   13588:        if(mle==1){
                   13589:          printf(" %.5le",matcov[i][j]);
                   13590:        }
                   13591:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13592:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13593:       }
                   13594:       fscanf(ficpar,"\n");
                   13595:       numlinepar++;
                   13596:       if(mle==1)
1.220     brouard  13597:                                printf("\n");
1.126     brouard  13598:       fprintf(ficlog,"\n");
                   13599:       fprintf(ficparo,"\n");
                   13600:     }
1.194     brouard  13601:     /* End of read covariance matrix npar lines */
1.126     brouard  13602:     for(i=1; i <=npar; i++)
                   13603:       for(j=i+1;j<=npar;j++)
1.226     brouard  13604:        matcov[i][j]=matcov[j][i];
1.126     brouard  13605:     
                   13606:     if(mle==1)
                   13607:       printf("\n");
                   13608:     fprintf(ficlog,"\n");
                   13609:     
                   13610:     fflush(ficlog);
                   13611:     
                   13612:   }    /* End of mle != -3 */
1.218     brouard  13613:   
1.186     brouard  13614:   /*  Main data
                   13615:    */
1.290     brouard  13616:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13617:   /* num=lvector(1,n); */
                   13618:   /* moisnais=vector(1,n); */
                   13619:   /* annais=vector(1,n); */
                   13620:   /* moisdc=vector(1,n); */
                   13621:   /* andc=vector(1,n); */
                   13622:   /* weight=vector(1,n); */
                   13623:   /* agedc=vector(1,n); */
                   13624:   /* cod=ivector(1,n); */
                   13625:   /* for(i=1;i<=n;i++){ */
                   13626:   num=lvector(firstobs,lastobs);
                   13627:   moisnais=vector(firstobs,lastobs);
                   13628:   annais=vector(firstobs,lastobs);
                   13629:   moisdc=vector(firstobs,lastobs);
                   13630:   andc=vector(firstobs,lastobs);
                   13631:   weight=vector(firstobs,lastobs);
                   13632:   agedc=vector(firstobs,lastobs);
                   13633:   cod=ivector(firstobs,lastobs);
                   13634:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13635:     num[i]=0;
                   13636:     moisnais[i]=0;
                   13637:     annais[i]=0;
                   13638:     moisdc[i]=0;
                   13639:     andc[i]=0;
                   13640:     agedc[i]=0;
                   13641:     cod[i]=0;
                   13642:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13643:   }
1.290     brouard  13644:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13645:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13646:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13647:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13648:   tab=ivector(1,NCOVMAX);
1.144     brouard  13649:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13650:   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  13651: 
1.136     brouard  13652:   /* Reads data from file datafile */
                   13653:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13654:     goto end;
                   13655: 
                   13656:   /* Calculation of the number of parameters from char model */
1.234     brouard  13657:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13658:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13659:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13660:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13661:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13662:   */
                   13663:   
                   13664:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13665:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13666:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13667:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13668:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13669:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13670:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13671:   TvarF=ivector(1,NCOVMAX); /*  */
                   13672:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13673:   TvarV=ivector(1,NCOVMAX); /*  */
                   13674:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13675:   TvarA=ivector(1,NCOVMAX); /*  */
                   13676:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13677:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13678:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13679:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13680:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13681:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13682:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13683:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13684:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13685:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13686:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13687:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13688:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13689:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13690:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13691: 
1.230     brouard  13692:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13693:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13694:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13695:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13696:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13697:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13698:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13699: 
1.137     brouard  13700:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13701:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13702:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13703:   */
                   13704:   /* For model-covariate k tells which data-covariate to use but
                   13705:     because this model-covariate is a construction we invent a new column
                   13706:     ncovcol + k1
                   13707:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13708:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13709:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13710:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13711:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13712:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13713:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13714:   */
1.145     brouard  13715:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13716:   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  13717:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13718:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351   ! brouard  13719:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13720:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13721:                         4 covariates (3 plus signs)
                   13722:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13723:                           */  
                   13724:   for(i=1;i<NCOVMAX;i++)
                   13725:     Tage[i]=0;
1.230     brouard  13726:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13727:                                * individual dummy, fixed or varying:
                   13728:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13729:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13730:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13731:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13732:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13733:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13734:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13735:                                * individual quantitative, fixed or varying:
                   13736:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13737:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13738:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13739: 
                   13740: /* Probably useless zeroes */
                   13741:   for(i=1;i<NCOVMAX;i++){
                   13742:     DummyV[i]=0;
                   13743:     FixedV[i]=0;
                   13744:   }
                   13745: 
                   13746:   for(i=1; i <=ncovcol;i++){
                   13747:     DummyV[i]=0;
                   13748:     FixedV[i]=0;
                   13749:   }
                   13750:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13751:     DummyV[i]=1;
                   13752:     FixedV[i]=0;
                   13753:   }
                   13754:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13755:     DummyV[i]=0;
                   13756:     FixedV[i]=1;
                   13757:   }
                   13758:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13759:     DummyV[i]=1;
                   13760:     FixedV[i]=1;
                   13761:   }
                   13762:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13763:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13764:     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]);
                   13765:   }
                   13766: 
                   13767: 
                   13768: 
1.186     brouard  13769: /* Main decodemodel */
                   13770: 
1.187     brouard  13771: 
1.223     brouard  13772:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13773:     goto end;
                   13774: 
1.137     brouard  13775:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13776:     nbwarn++;
                   13777:     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); 
                   13778:     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); 
                   13779:   }
1.136     brouard  13780:     /*  if(mle==1){*/
1.137     brouard  13781:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13782:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13783:   }
                   13784: 
                   13785:     /*-calculation of age at interview from date of interview and age at death -*/
                   13786:   agev=matrix(1,maxwav,1,imx);
                   13787: 
                   13788:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13789:     goto end;
                   13790: 
1.126     brouard  13791: 
1.136     brouard  13792:   agegomp=(int)agemin;
1.290     brouard  13793:   free_vector(moisnais,firstobs,lastobs);
                   13794:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13795:   /* free_matrix(mint,1,maxwav,1,n);
                   13796:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13797:   /* free_vector(moisdc,1,n); */
                   13798:   /* free_vector(andc,1,n); */
1.145     brouard  13799:   /* */
                   13800:   
1.126     brouard  13801:   wav=ivector(1,imx);
1.214     brouard  13802:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13803:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13804:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13805:   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.*/
                   13806:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13807:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13808:    
                   13809:   /* Concatenates waves */
1.214     brouard  13810:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13811:      Death is a valid wave (if date is known).
                   13812:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13813:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13814:      and mw[mi+1][i]. dh depends on stepm.
                   13815:   */
                   13816: 
1.126     brouard  13817:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13818:   /* Concatenates waves */
1.145     brouard  13819:  
1.290     brouard  13820:   free_vector(moisdc,firstobs,lastobs);
                   13821:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13822: 
1.126     brouard  13823:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13824:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13825:   ncodemax[1]=1;
1.145     brouard  13826:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13827:   cptcoveff=0;
1.220     brouard  13828:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13829:     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  13830:   }
                   13831:   
                   13832:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13833:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13834:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13835:     invalidvarcomb[i]=0;
                   13836:   
1.211     brouard  13837:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13838:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13839:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13840:   
1.200     brouard  13841:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13842:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13843:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13844:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13845:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13846:    * (currently 0 or 1) in the data.
                   13847:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13848:    * corresponding modality (h,j).
                   13849:    */
                   13850: 
1.145     brouard  13851:   h=0;
                   13852:   /*if (cptcovn > 0) */
1.126     brouard  13853:   m=pow(2,cptcoveff);
                   13854:  
1.144     brouard  13855:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13856:           * For k=4 covariates, h goes from 1 to m=2**k
                   13857:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13858:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13859:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13860:           *______________________________   *______________________
                   13861:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13862:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13863:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13864:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13865:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13866:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13867:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13868:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13869:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13870:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13871:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13872:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13873:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13874:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13875:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13876:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13877:           */                                     
1.212     brouard  13878:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13879:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13880:      * and the value of each covariate?
                   13881:      * V1=1, V2=1, V3=2, V4=1 ?
                   13882:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13883:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13884:      * In order to get the real value in the data, we use nbcode
                   13885:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13886:      * We are keeping this crazy system in order to be able (in the future?) 
                   13887:      * to have more than 2 values (0 or 1) for a covariate.
                   13888:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13889:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13890:      *              bbbbbbbb
                   13891:      *              76543210     
                   13892:      *   h-1        00000101 (6-1=5)
1.219     brouard  13893:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13894:      *           &
                   13895:      *     1        00000001 (1)
1.219     brouard  13896:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13897:      *          +1= 00000001 =1 
1.211     brouard  13898:      *
                   13899:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13900:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13901:      *    >>k'            11
                   13902:      *          &   00000001
                   13903:      *            = 00000001
                   13904:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13905:      * Reverse h=6 and m=16?
                   13906:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13907:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13908:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13909:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13910:      * V3=decodtabm(14,3,2**4)=2
                   13911:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13912:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13913:      *          &1 000000001
                   13914:      *           = 000000001
                   13915:      *         +1= 000000010 =2
                   13916:      *                  2211
                   13917:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13918:      *                  V3=2
1.220     brouard  13919:                 * codtabm and decodtabm are identical
1.211     brouard  13920:      */
                   13921: 
1.145     brouard  13922: 
                   13923:  free_ivector(Ndum,-1,NCOVMAX);
                   13924: 
                   13925: 
1.126     brouard  13926:     
1.186     brouard  13927:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13928:   strcpy(optionfilegnuplot,optionfilefiname);
                   13929:   if(mle==-3)
1.201     brouard  13930:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13931:   strcat(optionfilegnuplot,".gp");
                   13932: 
                   13933:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13934:     printf("Problem with file %s",optionfilegnuplot);
                   13935:   }
                   13936:   else{
1.204     brouard  13937:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13938:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13939:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13940:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13941:   }
                   13942:   /*  fclose(ficgp);*/
1.186     brouard  13943: 
                   13944: 
                   13945:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13946: 
                   13947:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13948:   if(mle==-3)
1.201     brouard  13949:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13950:   strcat(optionfilehtm,".htm");
                   13951:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13952:     printf("Problem with %s \n",optionfilehtm);
                   13953:     exit(0);
1.126     brouard  13954:   }
                   13955: 
                   13956:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13957:   strcat(optionfilehtmcov,"-cov.htm");
                   13958:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13959:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13960:   }
                   13961:   else{
                   13962:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13963: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13964: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13965:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13966:   }
                   13967: 
1.335     brouard  13968:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13969: <title>IMaCh %s</title></head>\n\
                   13970:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13971: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13972: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13973: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13974: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13975:   
                   13976:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13977: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13978: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13979: 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  13980: \n\
                   13981: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13982:  <ul><li><h4>Parameter files</h4>\n\
                   13983:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13984:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13985:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13986:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13987:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13988:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13989:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13990:          fileres,fileres,\
                   13991:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13992:   fflush(fichtm);
                   13993: 
                   13994:   strcpy(pathr,path);
                   13995:   strcat(pathr,optionfilefiname);
1.184     brouard  13996: #ifdef WIN32
                   13997:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13998: #else
1.126     brouard  13999:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14000: #endif
                   14001:          
1.126     brouard  14002:   
1.220     brouard  14003:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14004:                 and for any valid combination of covariates
1.126     brouard  14005:      and prints on file fileres'p'. */
1.251     brouard  14006:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14007:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14008: 
                   14009:   fprintf(fichtm,"\n");
1.286     brouard  14010:   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  14011:          ftol, stepm);
                   14012:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14013:   ncurrv=1;
                   14014:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14015:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14016:   ncurrv=i;
                   14017:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14018:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14019:   ncurrv=i;
                   14020:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14021:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14022:   ncurrv=i;
                   14023:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14024:   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", \
                   14025:           nlstate, ndeath, maxwav, mle, weightopt);
                   14026: 
                   14027:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14028: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14029: 
                   14030:   
1.317     brouard  14031:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14032: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14033: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14034:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14035:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14036:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14037:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14038:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14039:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14040: 
1.126     brouard  14041:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14042:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14043:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14044: 
                   14045:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14046:   /* For mortality only */
1.126     brouard  14047:   if (mle==-3){
1.136     brouard  14048:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14049:     for(i=1;i<=NDIM;i++)
                   14050:       for(j=1;j<=NDIM;j++)
                   14051:        ximort[i][j]=0.;
1.186     brouard  14052:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14053:     cens=ivector(firstobs,lastobs);
                   14054:     ageexmed=vector(firstobs,lastobs);
                   14055:     agecens=vector(firstobs,lastobs);
                   14056:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14057:                
1.126     brouard  14058:     for (i=1; i<=imx; i++){
                   14059:       dcwave[i]=-1;
                   14060:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14061:        if (s[m][i]>nlstate) {
                   14062:          dcwave[i]=m;
                   14063:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14064:          break;
                   14065:        }
1.126     brouard  14066:     }
1.226     brouard  14067:     
1.126     brouard  14068:     for (i=1; i<=imx; i++) {
                   14069:       if (wav[i]>0){
1.226     brouard  14070:        ageexmed[i]=agev[mw[1][i]][i];
                   14071:        j=wav[i];
                   14072:        agecens[i]=1.; 
                   14073:        
                   14074:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14075:          agecens[i]=agev[mw[j][i]][i];
                   14076:          cens[i]= 1;
                   14077:        }else if (ageexmed[i]< 1) 
                   14078:          cens[i]= -1;
                   14079:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14080:          cens[i]=0 ;
1.126     brouard  14081:       }
                   14082:       else cens[i]=-1;
                   14083:     }
                   14084:     
                   14085:     for (i=1;i<=NDIM;i++) {
                   14086:       for (j=1;j<=NDIM;j++)
1.226     brouard  14087:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14088:     }
                   14089:     
1.302     brouard  14090:     p[1]=0.0268; p[NDIM]=0.083;
                   14091:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14092:     
                   14093:     
1.136     brouard  14094: #ifdef GSL
                   14095:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14096: #else
1.126     brouard  14097:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14098: #endif
1.201     brouard  14099:     strcpy(filerespow,"POW-MORT_"); 
                   14100:     strcat(filerespow,fileresu);
1.126     brouard  14101:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14102:       printf("Problem with resultfile: %s\n", filerespow);
                   14103:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14104:     }
1.136     brouard  14105: #ifdef GSL
                   14106:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14107: #else
1.126     brouard  14108:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14109: #endif
1.126     brouard  14110:     /*  for (i=1;i<=nlstate;i++)
                   14111:        for(j=1;j<=nlstate+ndeath;j++)
                   14112:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14113:     */
                   14114:     fprintf(ficrespow,"\n");
1.136     brouard  14115: #ifdef GSL
                   14116:     /* gsl starts here */ 
                   14117:     T = gsl_multimin_fminimizer_nmsimplex;
                   14118:     gsl_multimin_fminimizer *sfm = NULL;
                   14119:     gsl_vector *ss, *x;
                   14120:     gsl_multimin_function minex_func;
                   14121: 
                   14122:     /* Initial vertex size vector */
                   14123:     ss = gsl_vector_alloc (NDIM);
                   14124:     
                   14125:     if (ss == NULL){
                   14126:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14127:     }
                   14128:     /* Set all step sizes to 1 */
                   14129:     gsl_vector_set_all (ss, 0.001);
                   14130: 
                   14131:     /* Starting point */
1.126     brouard  14132:     
1.136     brouard  14133:     x = gsl_vector_alloc (NDIM);
                   14134:     
                   14135:     if (x == NULL){
                   14136:       gsl_vector_free(ss);
                   14137:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14138:     }
                   14139:   
                   14140:     /* Initialize method and iterate */
                   14141:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14142:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14143:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14144:     gsl_vector_set(x, 0, p[1]);
                   14145:     gsl_vector_set(x, 1, p[2]);
                   14146: 
                   14147:     minex_func.f = &gompertz_f;
                   14148:     minex_func.n = NDIM;
                   14149:     minex_func.params = (void *)&p; /* ??? */
                   14150:     
                   14151:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14152:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14153:     
                   14154:     printf("Iterations beginning .....\n\n");
                   14155:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14156: 
                   14157:     iteri=0;
                   14158:     while (rval == GSL_CONTINUE){
                   14159:       iteri++;
                   14160:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14161:       
                   14162:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14163:       fflush(0);
                   14164:       
                   14165:       if (status) 
                   14166:         break;
                   14167:       
                   14168:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14169:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14170:       
                   14171:       if (rval == GSL_SUCCESS)
                   14172:         printf ("converged to a local maximum at\n");
                   14173:       
                   14174:       printf("%5d ", iteri);
                   14175:       for (it = 0; it < NDIM; it++){
                   14176:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14177:       }
                   14178:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14179:     }
                   14180:     
                   14181:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14182:     
                   14183:     gsl_vector_free(x); /* initial values */
                   14184:     gsl_vector_free(ss); /* inital step size */
                   14185:     for (it=0; it<NDIM; it++){
                   14186:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14187:       fprintf(ficrespow," %.12lf", p[it]);
                   14188:     }
                   14189:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14190: #endif
                   14191: #ifdef POWELL
                   14192:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14193: #endif  
1.126     brouard  14194:     fclose(ficrespow);
                   14195:     
1.203     brouard  14196:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14197: 
                   14198:     for(i=1; i <=NDIM; i++)
                   14199:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14200:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14201:     
                   14202:     printf("\nCovariance matrix\n ");
1.203     brouard  14203:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14204:     for(i=1; i <=NDIM; i++) {
                   14205:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14206:                                printf("%f ",matcov[i][j]);
                   14207:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14208:       }
1.203     brouard  14209:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14210:     }
                   14211:     
                   14212:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14213:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14214:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14215:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14216:     }
1.302     brouard  14217:     lsurv=vector(agegomp,AGESUP);
                   14218:     lpop=vector(agegomp,AGESUP);
                   14219:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14220:     lsurv[agegomp]=100000;
                   14221:     
                   14222:     for (k=agegomp;k<=AGESUP;k++) {
                   14223:       agemortsup=k;
                   14224:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14225:     }
                   14226:     
                   14227:     for (k=agegomp;k<agemortsup;k++)
                   14228:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14229:     
                   14230:     for (k=agegomp;k<agemortsup;k++){
                   14231:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14232:       sumlpop=sumlpop+lpop[k];
                   14233:     }
                   14234:     
                   14235:     tpop[agegomp]=sumlpop;
                   14236:     for (k=agegomp;k<(agemortsup-3);k++){
                   14237:       /*  tpop[k+1]=2;*/
                   14238:       tpop[k+1]=tpop[k]-lpop[k];
                   14239:     }
                   14240:     
                   14241:     
                   14242:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14243:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14244:       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]);
                   14245:     
                   14246:     
                   14247:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14248:                ageminpar=50;
                   14249:                agemaxpar=100;
1.194     brouard  14250:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14251:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14252: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14253: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14254:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14255: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14256: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14257:     }else{
                   14258:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14259:                        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  14260:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14261:                }
1.201     brouard  14262:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14263:                     stepm, weightopt,\
                   14264:                     model,imx,p,matcov,agemortsup);
                   14265:     
1.302     brouard  14266:     free_vector(lsurv,agegomp,AGESUP);
                   14267:     free_vector(lpop,agegomp,AGESUP);
                   14268:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14269:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14270:     free_ivector(dcwave,firstobs,lastobs);
                   14271:     free_vector(agecens,firstobs,lastobs);
                   14272:     free_vector(ageexmed,firstobs,lastobs);
                   14273:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14274: #ifdef GSL
1.136     brouard  14275: #endif
1.186     brouard  14276:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14277:   /* Standard  */
                   14278:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14279:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14280:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14281:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14282:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14283:     for (k=1; k<=npar;k++)
                   14284:       printf(" %d %8.5f",k,p[k]);
                   14285:     printf("\n");
1.205     brouard  14286:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14287:       /* mlikeli uses func not funcone */
1.247     brouard  14288:       /* for(i=1;i<nlstate;i++){ */
                   14289:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14290:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14291:       /* } */
1.205     brouard  14292:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14293:     }
                   14294:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14295:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14296:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14297:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14298:     }
                   14299:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14300:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14301:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14302:           /* exit(0); */
1.126     brouard  14303:     for (k=1; k<=npar;k++)
                   14304:       printf(" %d %8.5f",k,p[k]);
                   14305:     printf("\n");
                   14306:     
                   14307:     /*--------- results files --------------*/
1.283     brouard  14308:     /* 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  14309:     
                   14310:     
                   14311:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14312:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14313:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14314: 
                   14315:     printf("#model=  1      +     age ");
                   14316:     fprintf(ficres,"#model=  1      +     age ");
                   14317:     fprintf(ficlog,"#model=  1      +     age ");
                   14318:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14319: </ul>", model);
                   14320: 
                   14321:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14322:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14323:     if(nagesqr==1){
                   14324:       printf("  + age*age  ");
                   14325:       fprintf(ficres,"  + age*age  ");
                   14326:       fprintf(ficlog,"  + age*age  ");
                   14327:       fprintf(fichtm, "<th>+ age*age</th>");
                   14328:     }
                   14329:     for(j=1;j <=ncovmodel-2;j++){
                   14330:       if(Typevar[j]==0) {
                   14331:        printf("  +      V%d  ",Tvar[j]);
                   14332:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14333:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14334:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14335:       }else if(Typevar[j]==1) {
                   14336:        printf("  +    V%d*age ",Tvar[j]);
                   14337:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14338:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14339:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14340:       }else if(Typevar[j]==2) {
                   14341:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14342:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14343:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14344:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14345:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14346:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14347:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14348:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14349:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14350:       }
                   14351:     }
                   14352:     printf("\n");
                   14353:     fprintf(ficres,"\n");
                   14354:     fprintf(ficlog,"\n");
                   14355:     fprintf(fichtm, "</tr>");
                   14356:     fprintf(fichtm, "\n");
                   14357:     
                   14358:     
1.126     brouard  14359:     for(i=1,jk=1; i <=nlstate; i++){
                   14360:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14361:        if (k != i) {
1.319     brouard  14362:          fprintf(fichtm, "<tr>");
1.225     brouard  14363:          printf("%d%d ",i,k);
                   14364:          fprintf(ficlog,"%d%d ",i,k);
                   14365:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14366:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14367:          for(j=1; j <=ncovmodel; j++){
                   14368:            printf("%12.7f ",p[jk]);
                   14369:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14370:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14371:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14372:            jk++; 
                   14373:          }
                   14374:          printf("\n");
                   14375:          fprintf(ficlog,"\n");
                   14376:          fprintf(ficres,"\n");
1.319     brouard  14377:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14378:        }
1.126     brouard  14379:       }
                   14380:     }
1.319     brouard  14381:     /* fprintf(fichtm,"</tr>\n"); */
                   14382:     fprintf(fichtm,"</table>\n");
                   14383:     fprintf(fichtm, "\n");
                   14384: 
1.203     brouard  14385:     if(mle != 0){
                   14386:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14387:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14388:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14389:       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");
                   14390:       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  14391:       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  14392:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14393:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14394:       if(nagesqr==1){
                   14395:        printf("  + age*age  ");
                   14396:        fprintf(ficres,"  + age*age  ");
                   14397:        fprintf(ficlog,"  + age*age  ");
                   14398:        fprintf(fichtm, "<th>+ age*age</th>");
                   14399:       }
                   14400:       for(j=1;j <=ncovmodel-2;j++){
                   14401:        if(Typevar[j]==0) {
                   14402:          printf("  +      V%d  ",Tvar[j]);
                   14403:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14404:        }else if(Typevar[j]==1) {
                   14405:          printf("  +    V%d*age ",Tvar[j]);
                   14406:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14407:        }else if(Typevar[j]==2) {
                   14408:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14409:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14410:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14411:        }
                   14412:       }
                   14413:       fprintf(fichtm, "</tr>\n");
                   14414:  
1.203     brouard  14415:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14416:        for(k=1; k <=(nlstate+ndeath); k++){
                   14417:          if (k != i) {
1.319     brouard  14418:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14419:            printf("%d%d ",i,k);
                   14420:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14421:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14422:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14423:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14424:              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]));
                   14425:              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  14426:              if(fabs(wald) > 1.96){
1.321     brouard  14427:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14428:              }else{
                   14429:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14430:              }
1.324     brouard  14431:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14432:              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  14433:              jk++; 
                   14434:            }
                   14435:            printf("\n");
                   14436:            fprintf(ficlog,"\n");
1.319     brouard  14437:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14438:          }
                   14439:        }
1.193     brouard  14440:       }
1.203     brouard  14441:     } /* end of hesscov and Wald tests */
1.319     brouard  14442:     fprintf(fichtm,"</table>\n");
1.225     brouard  14443:     
1.203     brouard  14444:     /*  */
1.126     brouard  14445:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14446:     printf("# Scales (for hessian or gradient estimation)\n");
                   14447:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14448:     for(i=1,jk=1; i <=nlstate; i++){
                   14449:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14450:        if (j!=i) {
                   14451:          fprintf(ficres,"%1d%1d",i,j);
                   14452:          printf("%1d%1d",i,j);
                   14453:          fprintf(ficlog,"%1d%1d",i,j);
                   14454:          for(k=1; k<=ncovmodel;k++){
                   14455:            printf(" %.5e",delti[jk]);
                   14456:            fprintf(ficlog," %.5e",delti[jk]);
                   14457:            fprintf(ficres," %.5e",delti[jk]);
                   14458:            jk++;
                   14459:          }
                   14460:          printf("\n");
                   14461:          fprintf(ficlog,"\n");
                   14462:          fprintf(ficres,"\n");
                   14463:        }
1.126     brouard  14464:       }
                   14465:     }
                   14466:     
                   14467:     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  14468:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14469:       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");
                   14470:     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");
                   14471:     /* # 121 Var(a12)\n\ */
                   14472:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14473:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14474:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14475:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14476:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14477:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14478:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14479:     
                   14480:     
                   14481:     /* Just to have a covariance matrix which will be more understandable
                   14482:        even is we still don't want to manage dictionary of variables
                   14483:     */
                   14484:     for(itimes=1;itimes<=2;itimes++){
                   14485:       jj=0;
                   14486:       for(i=1; i <=nlstate; i++){
1.225     brouard  14487:        for(j=1; j <=nlstate+ndeath; j++){
                   14488:          if(j==i) continue;
                   14489:          for(k=1; k<=ncovmodel;k++){
                   14490:            jj++;
                   14491:            ca[0]= k+'a'-1;ca[1]='\0';
                   14492:            if(itimes==1){
                   14493:              if(mle>=1)
                   14494:                printf("#%1d%1d%d",i,j,k);
                   14495:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14496:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14497:            }else{
                   14498:              if(mle>=1)
                   14499:                printf("%1d%1d%d",i,j,k);
                   14500:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14501:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14502:            }
                   14503:            ll=0;
                   14504:            for(li=1;li <=nlstate; li++){
                   14505:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14506:                if(lj==li) continue;
                   14507:                for(lk=1;lk<=ncovmodel;lk++){
                   14508:                  ll++;
                   14509:                  if(ll<=jj){
                   14510:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14511:                    if(ll<jj){
                   14512:                      if(itimes==1){
                   14513:                        if(mle>=1)
                   14514:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14515:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14516:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14517:                      }else{
                   14518:                        if(mle>=1)
                   14519:                          printf(" %.5e",matcov[jj][ll]); 
                   14520:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14521:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14522:                      }
                   14523:                    }else{
                   14524:                      if(itimes==1){
                   14525:                        if(mle>=1)
                   14526:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14527:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14528:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14529:                      }else{
                   14530:                        if(mle>=1)
                   14531:                          printf(" %.7e",matcov[jj][ll]); 
                   14532:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14533:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14534:                      }
                   14535:                    }
                   14536:                  }
                   14537:                } /* end lk */
                   14538:              } /* end lj */
                   14539:            } /* end li */
                   14540:            if(mle>=1)
                   14541:              printf("\n");
                   14542:            fprintf(ficlog,"\n");
                   14543:            fprintf(ficres,"\n");
                   14544:            numlinepar++;
                   14545:          } /* end k*/
                   14546:        } /*end j */
1.126     brouard  14547:       } /* end i */
                   14548:     } /* end itimes */
                   14549:     
                   14550:     fflush(ficlog);
                   14551:     fflush(ficres);
1.225     brouard  14552:     while(fgets(line, MAXLINE, ficpar)) {
                   14553:       /* If line starts with a # it is a comment */
                   14554:       if (line[0] == '#') {
                   14555:        numlinepar++;
                   14556:        fputs(line,stdout);
                   14557:        fputs(line,ficparo);
                   14558:        fputs(line,ficlog);
1.299     brouard  14559:        fputs(line,ficres);
1.225     brouard  14560:        continue;
                   14561:       }else
                   14562:        break;
                   14563:     }
                   14564:     
1.209     brouard  14565:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14566:     /*   ungetc(c,ficpar); */
                   14567:     /*   fgets(line, MAXLINE, ficpar); */
                   14568:     /*   fputs(line,stdout); */
                   14569:     /*   fputs(line,ficparo); */
                   14570:     /* } */
                   14571:     /* ungetc(c,ficpar); */
1.126     brouard  14572:     
                   14573:     estepm=0;
1.209     brouard  14574:     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  14575:       
                   14576:       if (num_filled != 6) {
                   14577:        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);
                   14578:        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);
                   14579:        goto end;
                   14580:       }
                   14581:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14582:     }
                   14583:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14584:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14585:     
1.209     brouard  14586:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14587:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14588:     if (fage <= 2) {
                   14589:       bage = ageminpar;
                   14590:       fage = agemaxpar;
                   14591:     }
                   14592:     
                   14593:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14594:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14595:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14596:                
1.186     brouard  14597:     /* Other stuffs, more or less useful */    
1.254     brouard  14598:     while(fgets(line, MAXLINE, ficpar)) {
                   14599:       /* If line starts with a # it is a comment */
                   14600:       if (line[0] == '#') {
                   14601:        numlinepar++;
                   14602:        fputs(line,stdout);
                   14603:        fputs(line,ficparo);
                   14604:        fputs(line,ficlog);
1.299     brouard  14605:        fputs(line,ficres);
1.254     brouard  14606:        continue;
                   14607:       }else
                   14608:        break;
                   14609:     }
                   14610: 
                   14611:     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){
                   14612:       
                   14613:       if (num_filled != 7) {
                   14614:        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);
                   14615:        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);
                   14616:        goto end;
                   14617:       }
                   14618:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14619:       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);
                   14620:       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);
                   14621:       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  14622:     }
1.254     brouard  14623: 
                   14624:     while(fgets(line, MAXLINE, ficpar)) {
                   14625:       /* If line starts with a # it is a comment */
                   14626:       if (line[0] == '#') {
                   14627:        numlinepar++;
                   14628:        fputs(line,stdout);
                   14629:        fputs(line,ficparo);
                   14630:        fputs(line,ficlog);
1.299     brouard  14631:        fputs(line,ficres);
1.254     brouard  14632:        continue;
                   14633:       }else
                   14634:        break;
1.126     brouard  14635:     }
                   14636:     
                   14637:     
                   14638:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14639:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14640:     
1.254     brouard  14641:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14642:       if (num_filled != 1) {
                   14643:        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);
                   14644:        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);
                   14645:        goto end;
                   14646:       }
                   14647:       printf("pop_based=%d\n",popbased);
                   14648:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14649:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14650:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14651:     }
                   14652:      
1.258     brouard  14653:     /* Results */
1.332     brouard  14654:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14655:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14656:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14657:     endishere=0;
1.258     brouard  14658:     nresult=0;
1.308     brouard  14659:     parameterline=0;
1.258     brouard  14660:     do{
                   14661:       if(!fgets(line, MAXLINE, ficpar)){
                   14662:        endishere=1;
1.308     brouard  14663:        parameterline=15;
1.258     brouard  14664:       }else if (line[0] == '#') {
                   14665:        /* If line starts with a # it is a comment */
1.254     brouard  14666:        numlinepar++;
                   14667:        fputs(line,stdout);
                   14668:        fputs(line,ficparo);
                   14669:        fputs(line,ficlog);
1.299     brouard  14670:        fputs(line,ficres);
1.254     brouard  14671:        continue;
1.258     brouard  14672:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14673:        parameterline=11;
1.296     brouard  14674:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14675:        parameterline=12;
1.307     brouard  14676:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14677:        parameterline=13;
1.307     brouard  14678:       }
1.258     brouard  14679:       else{
                   14680:        parameterline=14;
1.254     brouard  14681:       }
1.308     brouard  14682:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14683:       case 11:
1.296     brouard  14684:        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)){
                   14685:                  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  14686:          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);
                   14687:          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);
                   14688:          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);
                   14689:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14690:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14691:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14692:           prvforecast = 1;
                   14693:        } 
                   14694:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14695:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14696:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14697:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14698:           prvforecast = 2;
                   14699:        }
                   14700:        else {
                   14701:          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);
                   14702:          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);
                   14703:          goto end;
1.258     brouard  14704:        }
1.254     brouard  14705:        break;
1.258     brouard  14706:       case 12:
1.296     brouard  14707:        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)){
                   14708:           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);
                   14709:          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);
                   14710:          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);
                   14711:          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);
                   14712:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14713:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14714:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14715:           prvbackcast = 1;
                   14716:        } 
                   14717:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14718:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14719:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14720:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14721:           prvbackcast = 2;
                   14722:        }
                   14723:        else {
                   14724:          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);
                   14725:          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);
                   14726:          goto end;
1.258     brouard  14727:        }
1.230     brouard  14728:        break;
1.258     brouard  14729:       case 13:
1.332     brouard  14730:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14731:        nresult++; /* Sum of resultlines */
1.342     brouard  14732:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14733:        /* removefirstspace(&resultlineori); */
                   14734:        
                   14735:        if(strstr(resultlineori,"v") !=0){
                   14736:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14737:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14738:          return 1;
                   14739:        }
                   14740:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14741:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14742:        if(nresult > MAXRESULTLINESPONE-1){
                   14743:          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);
                   14744:          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  14745:          goto end;
                   14746:        }
1.332     brouard  14747:        
1.310     brouard  14748:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14749:          fprintf(ficparo,"result: %s\n",resultline);
                   14750:          fprintf(ficres,"result: %s\n",resultline);
                   14751:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14752:        } else
                   14753:          goto end;
1.307     brouard  14754:        break;
                   14755:       case 14:
                   14756:        printf("Error: Unknown command '%s'\n",line);
                   14757:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14758:        if(line[0] == ' ' || line[0] == '\n'){
                   14759:          printf("It should not be an empty line '%s'\n",line);
                   14760:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14761:        }         
1.307     brouard  14762:        if(ncovmodel >=2 && nresult==0 ){
                   14763:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14764:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14765:        }
1.307     brouard  14766:        /* goto end; */
                   14767:        break;
1.308     brouard  14768:       case 15:
                   14769:        printf("End of resultlines.\n");
                   14770:        fprintf(ficlog,"End of resultlines.\n");
                   14771:        break;
                   14772:       default: /* parameterline =0 */
1.307     brouard  14773:        nresult=1;
                   14774:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14775:       } /* End switch parameterline */
                   14776:     }while(endishere==0); /* End do */
1.126     brouard  14777:     
1.230     brouard  14778:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14779:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14780:     
                   14781:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14782:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14783:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14784: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14785: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14786:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14787: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14788: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14789:     }else{
1.270     brouard  14790:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14791:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14792:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14793:       if(prvforecast==1){
                   14794:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14795:         jprojd=jproj1;
                   14796:         mprojd=mproj1;
                   14797:         anprojd=anproj1;
                   14798:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14799:         jprojf=jproj2;
                   14800:         mprojf=mproj2;
                   14801:         anprojf=anproj2;
                   14802:       } else if(prvforecast == 2){
                   14803:         dateprojd=dateintmean;
                   14804:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14805:         dateprojf=dateintmean+yrfproj;
                   14806:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14807:       }
                   14808:       if(prvbackcast==1){
                   14809:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14810:         jbackd=jback1;
                   14811:         mbackd=mback1;
                   14812:         anbackd=anback1;
                   14813:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14814:         jbackf=jback2;
                   14815:         mbackf=mback2;
                   14816:         anbackf=anback2;
                   14817:       } else if(prvbackcast == 2){
                   14818:         datebackd=dateintmean;
                   14819:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14820:         datebackf=dateintmean-yrbproj;
                   14821:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14822:       }
                   14823:       
1.350     brouard  14824:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14825:     }
                   14826:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14827:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14828:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14829:                
1.225     brouard  14830:     /*------------ free_vector  -------------*/
                   14831:     /*  chdir(path); */
1.220     brouard  14832:                
1.215     brouard  14833:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14834:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14835:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14836:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14837:     free_lvector(num,firstobs,lastobs);
                   14838:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14839:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14840:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14841:     fclose(ficparo);
                   14842:     fclose(ficres);
1.220     brouard  14843:                
                   14844:                
1.186     brouard  14845:     /* Other results (useful)*/
1.220     brouard  14846:                
                   14847:                
1.126     brouard  14848:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14849:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14850:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14851:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14852:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14853:     fclose(ficrespl);
                   14854: 
                   14855:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14856:     /*#include "hpijx.h"*/
1.332     brouard  14857:     /** 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?*/
                   14858:     /* calls hpxij with combination k */
1.180     brouard  14859:     hPijx(p, bage, fage);
1.145     brouard  14860:     fclose(ficrespij);
1.227     brouard  14861:     
1.220     brouard  14862:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14863:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14864:     k=1;
1.126     brouard  14865:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14866:     
1.269     brouard  14867:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14868:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14869:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14870:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14871:        for(k=1;k<=ncovcombmax;k++)
                   14872:          probs[i][j][k]=0.;
1.269     brouard  14873:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14874:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14875:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14876:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14877:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14878:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14879:          for(k=1;k<=ncovcombmax;k++)
                   14880:            mobaverages[i][j][k]=0.;
1.219     brouard  14881:       mobaverage=mobaverages;
                   14882:       if (mobilav!=0) {
1.235     brouard  14883:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14884:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14885:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14886:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14887:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14888:        }
1.269     brouard  14889:       } else if (mobilavproj !=0) {
1.235     brouard  14890:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14891:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14892:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14893:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14894:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14895:        }
1.269     brouard  14896:       }else{
                   14897:        printf("Internal error moving average\n");
                   14898:        fflush(stdout);
                   14899:        exit(1);
1.219     brouard  14900:       }
                   14901:     }/* end if moving average */
1.227     brouard  14902:     
1.126     brouard  14903:     /*---------- Forecasting ------------------*/
1.296     brouard  14904:     if(prevfcast==1){ 
                   14905:       /*   /\*    if(stepm ==1){*\/ */
                   14906:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14907:       /*This done previously after freqsummary.*/
                   14908:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14909:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14910:       
                   14911:       /* } else if (prvforecast==2){ */
                   14912:       /*   /\*    if(stepm ==1){*\/ */
                   14913:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14914:       /* } */
                   14915:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14916:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14917:     }
1.269     brouard  14918: 
1.296     brouard  14919:     /* Prevbcasting */
                   14920:     if(prevbcast==1){
1.219     brouard  14921:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14922:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14923:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14924: 
                   14925:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14926: 
                   14927:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14928: 
1.219     brouard  14929:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14930:       fclose(ficresplb);
                   14931: 
1.222     brouard  14932:       hBijx(p, bage, fage, mobaverage);
                   14933:       fclose(ficrespijb);
1.219     brouard  14934: 
1.296     brouard  14935:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14936:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14937:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14938:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14939:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14940:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14941: 
                   14942:       
1.269     brouard  14943:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14944: 
                   14945:       
1.269     brouard  14946:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14947:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14948:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14949:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14950:     }    /* end  Prevbcasting */
1.268     brouard  14951:  
1.186     brouard  14952:  
                   14953:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14954: 
1.215     brouard  14955:     free_ivector(wav,1,imx);
                   14956:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14957:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14958:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14959:                
                   14960:                
1.127     brouard  14961:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14962:                
1.201     brouard  14963:     strcpy(filerese,"E_");
                   14964:     strcat(filerese,fileresu);
1.126     brouard  14965:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14966:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14967:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14968:     }
1.208     brouard  14969:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14970:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14971: 
                   14972:     pstamp(ficreseij);
1.219     brouard  14973:                
1.351   ! brouard  14974:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
        !          14975:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  14976:     
1.351   ! brouard  14977:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          14978:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
        !          14979:       /* if(i1 != 1 && TKresult[nres]!= k) */
        !          14980:       /*       continue; */
1.219     brouard  14981:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14982:       printf("\n#****** ");
1.351   ! brouard  14983:       for(j=1;j<=cptcovs;j++){
        !          14984:       /* for(j=1;j<=cptcoveff;j++) { */
        !          14985:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          14986:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          14987:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          14988:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  14989:       }
                   14990:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14991:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14992:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14993:       }
                   14994:       fprintf(ficreseij,"******\n");
1.235     brouard  14995:       printf("******\n");
1.219     brouard  14996:       
                   14997:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14998:       oldm=oldms;savm=savms;
1.330     brouard  14999:       /* 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  15000:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15001:       
1.219     brouard  15002:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15003:     }
                   15004:     fclose(ficreseij);
1.208     brouard  15005:     printf("done evsij\n");fflush(stdout);
                   15006:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15007: 
1.218     brouard  15008:                
1.227     brouard  15009:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15010:     /* Should be moved in a function */                
1.201     brouard  15011:     strcpy(filerest,"T_");
                   15012:     strcat(filerest,fileresu);
1.127     brouard  15013:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15014:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15015:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15016:     }
1.208     brouard  15017:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15018:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15019:     strcpy(fileresstde,"STDE_");
                   15020:     strcat(fileresstde,fileresu);
1.126     brouard  15021:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15022:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15023:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15024:     }
1.227     brouard  15025:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15026:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15027: 
1.201     brouard  15028:     strcpy(filerescve,"CVE_");
                   15029:     strcat(filerescve,fileresu);
1.126     brouard  15030:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15031:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15032:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15033:     }
1.227     brouard  15034:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15035:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15036: 
1.201     brouard  15037:     strcpy(fileresv,"V_");
                   15038:     strcat(fileresv,fileresu);
1.126     brouard  15039:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15040:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15041:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15042:     }
1.227     brouard  15043:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15044:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15045: 
1.235     brouard  15046:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15047:     if (cptcovn < 1){i1=1;}
                   15048:     
1.334     brouard  15049:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15050:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15051:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15052:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15053:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15054:       /* */
                   15055:       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  15056:        continue;
1.350     brouard  15057:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15058:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15059:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15060:       /* It might not be a good idea to mix dummies and quantitative */
                   15061:       /* 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 *\/ */
                   15062:       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 */
                   15063:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15064:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15065:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15066:         * (V5 is quanti) V4 and V3 are dummies
                   15067:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15068:         *                                                              l=1 l=2
                   15069:         *                                                           k=1  1   1   0   0
                   15070:         *                                                           k=2  2   1   1   0
                   15071:         *                                                           k=3 [1] [2]  0   1
                   15072:         *                                                           k=4  2   2   1   1
                   15073:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15074:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15075:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15076:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15077:         */
                   15078:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15079:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15080: /* We give up with the combinations!! */
1.342     brouard  15081:        /* if(debugILK) */
                   15082:        /*   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  15083: 
                   15084:        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  15085:          /* 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] */
                   15086:          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  */
                   15087:          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  */
                   15088:          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  15089:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15090:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15091:          }else{
                   15092:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15093:          }
                   15094:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15095:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15096:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15097:          /* For each selected (single) quantitative value */
1.337     brouard  15098:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15099:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15100:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15101:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15102:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15103:          }else{
                   15104:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15105:          }
                   15106:        }else{
                   15107:          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 */
                   15108:          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 */
                   15109:          exit(1);
                   15110:        }
1.335     brouard  15111:       } /* End loop for each variable in the resultline */
1.334     brouard  15112:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15113:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15114:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15115:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15116:       /* }      */
1.208     brouard  15117:       fprintf(ficrest,"******\n");
1.227     brouard  15118:       fprintf(ficlog,"******\n");
                   15119:       printf("******\n");
1.208     brouard  15120:       
                   15121:       fprintf(ficresstdeij,"\n#****** ");
                   15122:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15123:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15124:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15125:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15126:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15127:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15128:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15129:       }
                   15130:       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  15131:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15132:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15133:       }        
1.208     brouard  15134:       fprintf(ficresstdeij,"******\n");
                   15135:       fprintf(ficrescveij,"******\n");
                   15136:       
                   15137:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15138:       /* pstamp(ficresvij); */
1.225     brouard  15139:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15140:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15141:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15142:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15143:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15144:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15145:       }        
1.208     brouard  15146:       fprintf(ficresvij,"******\n");
                   15147:       
                   15148:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15149:       oldm=oldms;savm=savms;
1.235     brouard  15150:       printf(" cvevsij ");
                   15151:       fprintf(ficlog, " cvevsij ");
                   15152:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15153:       printf(" end cvevsij \n ");
                   15154:       fprintf(ficlog, " end cvevsij \n ");
                   15155:       
                   15156:       /*
                   15157:        */
                   15158:       /* goto endfree; */
                   15159:       
                   15160:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15161:       pstamp(ficrest);
                   15162:       
1.269     brouard  15163:       epj=vector(1,nlstate+1);
1.208     brouard  15164:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15165:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15166:        cptcod= 0; /* To be deleted */
                   15167:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15168:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15169:        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  15170:        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 ");
                   15171:        if(vpopbased==1)
                   15172:          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);
                   15173:        else
1.288     brouard  15174:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15175:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15176:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15177:        fprintf(ficrest,"\n");
                   15178:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15179:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15180:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15181:        for(age=bage; age <=fage ;age++){
1.235     brouard  15182:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15183:          if (vpopbased==1) {
                   15184:            if(mobilav ==0){
                   15185:              for(i=1; i<=nlstate;i++)
                   15186:                prlim[i][i]=probs[(int)age][i][k];
                   15187:            }else{ /* mobilav */ 
                   15188:              for(i=1; i<=nlstate;i++)
                   15189:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15190:            }
                   15191:          }
1.219     brouard  15192:          
1.227     brouard  15193:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15194:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15195:          /* printf(" age %4.0f ",age); */
                   15196:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15197:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15198:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15199:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15200:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15201:            }
                   15202:            epj[nlstate+1] +=epj[j];
                   15203:          }
                   15204:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15205:          
1.227     brouard  15206:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15207:            for(j=1;j <=nlstate;j++)
                   15208:              vepp += vareij[i][j][(int)age];
                   15209:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15210:          for(j=1;j <=nlstate;j++){
                   15211:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15212:          }
                   15213:          fprintf(ficrest,"\n");
                   15214:        }
1.208     brouard  15215:       } /* End vpopbased */
1.269     brouard  15216:       free_vector(epj,1,nlstate+1);
1.208     brouard  15217:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15218:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15219:       printf("done selection\n");fflush(stdout);
                   15220:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15221:       
1.335     brouard  15222:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15223: 
                   15224:     printf("done State-specific expectancies\n");fflush(stdout);
                   15225:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15226: 
1.335     brouard  15227:     /* variance-covariance of forward period prevalence */
1.269     brouard  15228:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15229: 
1.227     brouard  15230:     
1.290     brouard  15231:     free_vector(weight,firstobs,lastobs);
1.351   ! brouard  15232:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15233:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15234:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15235:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15236:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15237:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15238:     free_ivector(tab,1,NCOVMAX);
                   15239:     fclose(ficresstdeij);
                   15240:     fclose(ficrescveij);
                   15241:     fclose(ficresvij);
                   15242:     fclose(ficrest);
                   15243:     fclose(ficpar);
                   15244:     
                   15245:     
1.126     brouard  15246:     /*---------- End : free ----------------*/
1.219     brouard  15247:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15248:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15249:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15250:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15251:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15252:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15253:   /* endfree:*/
                   15254:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15255:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15256:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15257:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15258:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15259:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15260:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15261:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15262:   free_matrix(matcov,1,npar,1,npar);
                   15263:   free_matrix(hess,1,npar,1,npar);
                   15264:   /*free_vector(delti,1,npar);*/
                   15265:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15266:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15267:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15268:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15269:   
                   15270:   free_ivector(ncodemax,1,NCOVMAX);
                   15271:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15272:   free_ivector(Dummy,-1,NCOVMAX);
                   15273:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15274:   free_ivector(DummyV,-1,NCOVMAX);
                   15275:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15276:   free_ivector(Typevar,-1,NCOVMAX);
                   15277:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15278:   free_ivector(TvarsQ,1,NCOVMAX);
                   15279:   free_ivector(TvarsQind,1,NCOVMAX);
                   15280:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15281:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15282:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15283:   free_ivector(TvarFD,1,NCOVMAX);
                   15284:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15285:   free_ivector(TvarF,1,NCOVMAX);
                   15286:   free_ivector(TvarFind,1,NCOVMAX);
                   15287:   free_ivector(TvarV,1,NCOVMAX);
                   15288:   free_ivector(TvarVind,1,NCOVMAX);
                   15289:   free_ivector(TvarA,1,NCOVMAX);
                   15290:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15291:   free_ivector(TvarFQ,1,NCOVMAX);
                   15292:   free_ivector(TvarFQind,1,NCOVMAX);
                   15293:   free_ivector(TvarVD,1,NCOVMAX);
                   15294:   free_ivector(TvarVDind,1,NCOVMAX);
                   15295:   free_ivector(TvarVQ,1,NCOVMAX);
                   15296:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15297:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15298:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15299:   free_ivector(TvarVVA,1,NCOVMAX);
                   15300:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15301:   free_ivector(TvarVV,1,NCOVMAX);
                   15302:   free_ivector(TvarVVind,1,NCOVMAX);
                   15303:   
1.230     brouard  15304:   free_ivector(Tvarsel,1,NCOVMAX);
                   15305:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15306:   free_ivector(Tposprod,1,NCOVMAX);
                   15307:   free_ivector(Tprod,1,NCOVMAX);
                   15308:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15309:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15310:   free_ivector(Tage,1,NCOVMAX);
                   15311:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15312:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15313:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15314: 
                   15315:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15316: 
1.227     brouard  15317:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15318:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15319:   fflush(fichtm);
                   15320:   fflush(ficgp);
                   15321:   
1.227     brouard  15322:   
1.126     brouard  15323:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15324:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15325:     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  15326:   }else{
                   15327:     printf("End of Imach\n");
                   15328:     fprintf(ficlog,"End of Imach\n");
                   15329:   }
                   15330:   printf("See log file on %s\n",filelog);
                   15331:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15332:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15333:   rend_time = time(NULL);  
                   15334:   end_time = *localtime(&rend_time);
                   15335:   /* tml = *localtime(&end_time.tm_sec); */
                   15336:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15337:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15338:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15339:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15340:   
1.157     brouard  15341:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15342:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15343:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15344:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15345: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15346:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15347:   fclose(fichtm);
                   15348:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15349:   fclose(fichtmcov);
                   15350:   fclose(ficgp);
                   15351:   fclose(ficlog);
                   15352:   /*------ End -----------*/
1.227     brouard  15353:   
1.281     brouard  15354: 
                   15355: /* Executes gnuplot */
1.227     brouard  15356:   
                   15357:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15358: #ifdef WIN32
1.227     brouard  15359:   if (_chdir(pathcd) != 0)
                   15360:     printf("Can't move to directory %s!\n",path);
                   15361:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15362: #else
1.227     brouard  15363:     if(chdir(pathcd) != 0)
                   15364:       printf("Can't move to directory %s!\n", path);
                   15365:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15366: #endif 
1.126     brouard  15367:     printf("Current directory %s!\n",pathcd);
                   15368:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15369:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15370: #ifdef _WIN32
1.126     brouard  15371:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15372: #endif
                   15373:   if(!stat(plotcmd,&info)){
1.158     brouard  15374:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15375:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15376:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15377:     }else
                   15378:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15379: #ifdef __unix
1.126     brouard  15380:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15381:     if(!stat(plotcmd,&info)){
1.158     brouard  15382:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15383:     }else
                   15384:       strcpy(pplotcmd,plotcmd);
                   15385: #endif
                   15386:   }else
                   15387:     strcpy(pplotcmd,plotcmd);
                   15388:   
                   15389:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15390:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15391:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15392:   
1.126     brouard  15393:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15394:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15395:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15396:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15397:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15398:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15399:       strcpy(plotcmd,pplotcmd);
                   15400:     }
1.126     brouard  15401:   }
1.158     brouard  15402:   printf(" Successful, please wait...");
1.126     brouard  15403:   while (z[0] != 'q') {
                   15404:     /* chdir(path); */
1.154     brouard  15405:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15406:     scanf("%s",z);
                   15407: /*     if (z[0] == 'c') system("./imach"); */
                   15408:     if (z[0] == 'e') {
1.158     brouard  15409: #ifdef __APPLE__
1.152     brouard  15410:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15411: #elif __linux
                   15412:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15413: #else
1.152     brouard  15414:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15415: #endif
                   15416:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15417:       system(pplotcmd);
1.126     brouard  15418:     }
                   15419:     else if (z[0] == 'g') system(plotcmd);
                   15420:     else if (z[0] == 'q') exit(0);
                   15421:   }
1.227     brouard  15422: end:
1.126     brouard  15423:   while (z[0] != 'q') {
1.195     brouard  15424:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15425:     scanf("%s",z);
                   15426:   }
1.283     brouard  15427:   printf("End\n");
1.282     brouard  15428:   exit(0);
1.126     brouard  15429: }

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