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

1.350   ! brouard     1: /* $Id: imach.c,v 1.349 2023/01/31 09:19:37 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.350   ! brouard     4:   Revision 1.349  2023/01/31 09:19:37  brouard
        !             5:   Summary: Improvements in models with age*Vn*Vm
        !             6: 
1.348     brouard     7:   Revision 1.347  2022/09/18 14:36:44  brouard
                      8:   Summary: version 0.99r42
                      9: 
1.347     brouard    10:   Revision 1.346  2022/09/16 13:52:36  brouard
                     11:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     12: 
1.346     brouard    13:   Revision 1.345  2022/09/16 13:40:11  brouard
                     14:   Summary: Version 0.99r41
                     15: 
                     16:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     17: 
1.345     brouard    18:   Revision 1.344  2022/09/14 19:33:30  brouard
                     19:   Summary: version 0.99r40
                     20: 
                     21:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     22: 
1.344     brouard    23:   Revision 1.343  2022/09/14 14:22:16  brouard
                     24:   Summary: version 0.99r39
                     25: 
                     26:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     27:   (fixed or time varying), using new last columns of
                     28:   ILK_parameter.txt file.
                     29: 
1.343     brouard    30:   Revision 1.342  2022/09/11 19:54:09  brouard
                     31:   Summary: 0.99r38
                     32: 
                     33:   * imach.c (Module): Adding timevarying products of any kinds,
                     34:   should work before shifting cotvar from ncovcol+nqv columns in
                     35:   order to have a correspondance between the column of cotvar and
                     36:   the id of column.
                     37:   (Module): Some cleaning and adding covariates in ILK.txt
                     38: 
1.342     brouard    39:   Revision 1.341  2022/09/11 07:58:42  brouard
                     40:   Summary: Version 0.99r38
                     41: 
                     42:   After adding change in cotvar.
                     43: 
1.341     brouard    44:   Revision 1.340  2022/09/11 07:53:11  brouard
                     45:   Summary: Version imach 0.99r37
                     46: 
                     47:   * imach.c (Module): Adding timevarying products of any kinds,
                     48:   should work before shifting cotvar from ncovcol+nqv columns in
                     49:   order to have a correspondance between the column of cotvar and
                     50:   the id of column.
                     51: 
1.340     brouard    52:   Revision 1.339  2022/09/09 17:55:22  brouard
                     53:   Summary: version 0.99r37
                     54: 
                     55:   * imach.c (Module): Many improvements for fixing products of fixed
                     56:   timevarying as well as fixed * fixed, and test with quantitative
                     57:   covariate.
                     58: 
1.339     brouard    59:   Revision 1.338  2022/09/04 17:40:33  brouard
                     60:   Summary: 0.99r36
                     61: 
                     62:   * imach.c (Module): Now the easy runs i.e. without result or
                     63:   model=1+age only did not work. The defautl combination should be 1
                     64:   and not 0 because everything hasn't been tranformed yet.
                     65: 
1.338     brouard    66:   Revision 1.337  2022/09/02 14:26:02  brouard
                     67:   Summary: version 0.99r35
                     68: 
                     69:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     70:   1+age+V1+V1*age for females and 1+age for females only
                     71:   (education=1 noweight)
                     72: 
1.337     brouard    73:   Revision 1.336  2022/08/31 09:52:36  brouard
                     74:   *** empty log message ***
                     75: 
1.336     brouard    76:   Revision 1.335  2022/08/31 08:23:16  brouard
                     77:   Summary: improvements...
                     78: 
1.335     brouard    79:   Revision 1.334  2022/08/25 09:08:41  brouard
                     80:   Summary: In progress for quantitative
                     81: 
1.334     brouard    82:   Revision 1.333  2022/08/21 09:10:30  brouard
                     83:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     84:   reassigning covariates: my first idea was that people will always
                     85:   use the first covariate V1 into the model but in fact they are
                     86:   producing data with many covariates and can use an equation model
                     87:   with some of the covariate; it means that in a model V2+V3 instead
                     88:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     89:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     90:   the equation model is restricted to two variables only (V2, V3)
                     91:   and the combination for V2 should be codtabm(k,1) instead of
                     92:   (codtabm(k,2), and the code should be
                     93:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     94:   made. All of these should be simplified once a day like we did in
                     95:   hpxij() for example by using precov[nres] which is computed in
                     96:   decoderesult for each nres of each resultline. Loop should be done
                     97:   on the equation model globally by distinguishing only product with
                     98:   age (which are changing with age) and no more on type of
                     99:   covariates, single dummies, single covariates.
                    100: 
1.333     brouard   101:   Revision 1.332  2022/08/21 09:06:25  brouard
                    102:   Summary: Version 0.99r33
                    103: 
                    104:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    105:   reassigning covariates: my first idea was that people will always
                    106:   use the first covariate V1 into the model but in fact they are
                    107:   producing data with many covariates and can use an equation model
                    108:   with some of the covariate; it means that in a model V2+V3 instead
                    109:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    110:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    111:   the equation model is restricted to two variables only (V2, V3)
                    112:   and the combination for V2 should be codtabm(k,1) instead of
                    113:   (codtabm(k,2), and the code should be
                    114:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    115:   made. All of these should be simplified once a day like we did in
                    116:   hpxij() for example by using precov[nres] which is computed in
                    117:   decoderesult for each nres of each resultline. Loop should be done
                    118:   on the equation model globally by distinguishing only product with
                    119:   age (which are changing with age) and no more on type of
                    120:   covariates, single dummies, single covariates.
                    121: 
1.332     brouard   122:   Revision 1.331  2022/08/07 05:40:09  brouard
                    123:   *** empty log message ***
                    124: 
1.331     brouard   125:   Revision 1.330  2022/08/06 07:18:25  brouard
                    126:   Summary: last 0.99r31
                    127: 
                    128:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    129: 
1.330     brouard   130:   Revision 1.329  2022/08/03 17:29:54  brouard
                    131:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    132: 
1.329     brouard   133:   Revision 1.328  2022/07/27 17:40:48  brouard
                    134:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    135: 
1.328     brouard   136:   Revision 1.327  2022/07/27 14:47:35  brouard
                    137:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    138: 
1.327     brouard   139:   Revision 1.326  2022/07/26 17:33:55  brouard
                    140:   Summary: some test with nres=1
                    141: 
1.326     brouard   142:   Revision 1.325  2022/07/25 14:27:23  brouard
                    143:   Summary: r30
                    144: 
                    145:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    146:   coredumped, revealed by Feiuno, thank you.
                    147: 
1.325     brouard   148:   Revision 1.324  2022/07/23 17:44:26  brouard
                    149:   *** empty log message ***
                    150: 
1.324     brouard   151:   Revision 1.323  2022/07/22 12:30:08  brouard
                    152:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    153: 
1.323     brouard   154:   Revision 1.322  2022/07/22 12:27:48  brouard
                    155:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    156: 
1.322     brouard   157:   Revision 1.321  2022/07/22 12:04:24  brouard
                    158:   Summary: r28
                    159: 
                    160:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    161: 
1.321     brouard   162:   Revision 1.320  2022/06/02 05:10:11  brouard
                    163:   *** empty log message ***
                    164: 
1.320     brouard   165:   Revision 1.319  2022/06/02 04:45:11  brouard
                    166:   * imach.c (Module): Adding the Wald tests from the log to the main
                    167:   htm for better display of the maximum likelihood estimators.
                    168: 
1.319     brouard   169:   Revision 1.318  2022/05/24 08:10:59  brouard
                    170:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    171:   of confidencce intervals with product in the equation modelC
                    172: 
1.318     brouard   173:   Revision 1.317  2022/05/15 15:06:23  brouard
                    174:   * imach.c (Module):  Some minor improvements
                    175: 
1.317     brouard   176:   Revision 1.316  2022/05/11 15:11:31  brouard
                    177:   Summary: r27
                    178: 
1.316     brouard   179:   Revision 1.315  2022/05/11 15:06:32  brouard
                    180:   *** empty log message ***
                    181: 
1.315     brouard   182:   Revision 1.314  2022/04/13 17:43:09  brouard
                    183:   * imach.c (Module): Adding link to text data files
                    184: 
1.314     brouard   185:   Revision 1.313  2022/04/11 15:57:42  brouard
                    186:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    187: 
1.313     brouard   188:   Revision 1.312  2022/04/05 21:24:39  brouard
                    189:   *** empty log message ***
                    190: 
1.312     brouard   191:   Revision 1.311  2022/04/05 21:03:51  brouard
                    192:   Summary: Fixed quantitative covariates
                    193: 
                    194:          Fixed covariates (dummy or quantitative)
                    195:        with missing values have never been allowed but are ERRORS and
                    196:        program quits. Standard deviations of fixed covariates were
                    197:        wrongly computed. Mean and standard deviations of time varying
                    198:        covariates are still not computed.
                    199: 
1.311     brouard   200:   Revision 1.310  2022/03/17 08:45:53  brouard
                    201:   Summary: 99r25
                    202: 
                    203:   Improving detection of errors: result lines should be compatible with
                    204:   the model.
                    205: 
1.310     brouard   206:   Revision 1.309  2021/05/20 12:39:14  brouard
                    207:   Summary: Version 0.99r24
                    208: 
1.309     brouard   209:   Revision 1.308  2021/03/31 13:11:57  brouard
                    210:   Summary: Version 0.99r23
                    211: 
                    212: 
                    213:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    214: 
1.308     brouard   215:   Revision 1.307  2021/03/08 18:11:32  brouard
                    216:   Summary: 0.99r22 fixed bug on result:
                    217: 
1.307     brouard   218:   Revision 1.306  2021/02/20 15:44:02  brouard
                    219:   Summary: Version 0.99r21
                    220: 
                    221:   * imach.c (Module): Fix bug on quitting after result lines!
                    222:   (Module): Version 0.99r21
                    223: 
1.306     brouard   224:   Revision 1.305  2021/02/20 15:28:30  brouard
                    225:   * imach.c (Module): Fix bug on quitting after result lines!
                    226: 
1.305     brouard   227:   Revision 1.304  2021/02/12 11:34:20  brouard
                    228:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    229: 
1.304     brouard   230:   Revision 1.303  2021/02/11 19:50:15  brouard
                    231:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    232: 
1.303     brouard   233:   Revision 1.302  2020/02/22 21:00:05  brouard
                    234:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    235:   and life table from the data without any state)
                    236: 
1.302     brouard   237:   Revision 1.301  2019/06/04 13:51:20  brouard
                    238:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    239: 
1.301     brouard   240:   Revision 1.300  2019/05/22 19:09:45  brouard
                    241:   Summary: version 0.99r19 of May 2019
                    242: 
1.300     brouard   243:   Revision 1.299  2019/05/22 18:37:08  brouard
                    244:   Summary: Cleaned 0.99r19
                    245: 
1.299     brouard   246:   Revision 1.298  2019/05/22 18:19:56  brouard
                    247:   *** empty log message ***
                    248: 
1.298     brouard   249:   Revision 1.297  2019/05/22 17:56:10  brouard
                    250:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    251: 
1.297     brouard   252:   Revision 1.296  2019/05/20 13:03:18  brouard
                    253:   Summary: Projection syntax simplified
                    254: 
                    255: 
                    256:   We can now start projections, forward or backward, from the mean date
                    257:   of inteviews up to or down to a number of years of projection:
                    258:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    259:   or
                    260:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    261:   or
                    262:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    263:   or
                    264:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    265: 
1.296     brouard   266:   Revision 1.295  2019/05/18 09:52:50  brouard
                    267:   Summary: doxygen tex bug
                    268: 
1.295     brouard   269:   Revision 1.294  2019/05/16 14:54:33  brouard
                    270:   Summary: There was some wrong lines added
                    271: 
1.294     brouard   272:   Revision 1.293  2019/05/09 15:17:34  brouard
                    273:   *** empty log message ***
                    274: 
1.293     brouard   275:   Revision 1.292  2019/05/09 14:17:20  brouard
                    276:   Summary: Some updates
                    277: 
1.292     brouard   278:   Revision 1.291  2019/05/09 13:44:18  brouard
                    279:   Summary: Before ncovmax
                    280: 
1.291     brouard   281:   Revision 1.290  2019/05/09 13:39:37  brouard
                    282:   Summary: 0.99r18 unlimited number of individuals
                    283: 
                    284:   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.
                    285: 
1.290     brouard   286:   Revision 1.289  2018/12/13 09:16:26  brouard
                    287:   Summary: Bug for young ages (<-30) will be in r17
                    288: 
1.289     brouard   289:   Revision 1.288  2018/05/02 20:58:27  brouard
                    290:   Summary: Some bugs fixed
                    291: 
1.288     brouard   292:   Revision 1.287  2018/05/01 17:57:25  brouard
                    293:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    294: 
1.287     brouard   295:   Revision 1.286  2018/04/27 14:27:04  brouard
                    296:   Summary: some minor bugs
                    297: 
1.286     brouard   298:   Revision 1.285  2018/04/21 21:02:16  brouard
                    299:   Summary: Some bugs fixed, valgrind tested
                    300: 
1.285     brouard   301:   Revision 1.284  2018/04/20 05:22:13  brouard
                    302:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    303: 
1.284     brouard   304:   Revision 1.283  2018/04/19 14:49:16  brouard
                    305:   Summary: Some minor bugs fixed
                    306: 
1.283     brouard   307:   Revision 1.282  2018/02/27 22:50:02  brouard
                    308:   *** empty log message ***
                    309: 
1.282     brouard   310:   Revision 1.281  2018/02/27 19:25:23  brouard
                    311:   Summary: Adding second argument for quitting
                    312: 
1.281     brouard   313:   Revision 1.280  2018/02/21 07:58:13  brouard
                    314:   Summary: 0.99r15
                    315: 
                    316:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    317: 
1.280     brouard   318:   Revision 1.279  2017/07/20 13:35:01  brouard
                    319:   Summary: temporary working
                    320: 
1.279     brouard   321:   Revision 1.278  2017/07/19 14:09:02  brouard
                    322:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    323: 
1.278     brouard   324:   Revision 1.277  2017/07/17 08:53:49  brouard
                    325:   Summary: BOM files can be read now
                    326: 
1.277     brouard   327:   Revision 1.276  2017/06/30 15:48:31  brouard
                    328:   Summary: Graphs improvements
                    329: 
1.276     brouard   330:   Revision 1.275  2017/06/30 13:39:33  brouard
                    331:   Summary: Saito's color
                    332: 
1.275     brouard   333:   Revision 1.274  2017/06/29 09:47:08  brouard
                    334:   Summary: Version 0.99r14
                    335: 
1.274     brouard   336:   Revision 1.273  2017/06/27 11:06:02  brouard
                    337:   Summary: More documentation on projections
                    338: 
1.273     brouard   339:   Revision 1.272  2017/06/27 10:22:40  brouard
                    340:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    341: 
1.272     brouard   342:   Revision 1.271  2017/06/27 10:17:50  brouard
                    343:   Summary: Some bug with rint
                    344: 
1.271     brouard   345:   Revision 1.270  2017/05/24 05:45:29  brouard
                    346:   *** empty log message ***
                    347: 
1.270     brouard   348:   Revision 1.269  2017/05/23 08:39:25  brouard
                    349:   Summary: Code into subroutine, cleanings
                    350: 
1.269     brouard   351:   Revision 1.268  2017/05/18 20:09:32  brouard
                    352:   Summary: backprojection and confidence intervals of backprevalence
                    353: 
1.268     brouard   354:   Revision 1.267  2017/05/13 10:25:05  brouard
                    355:   Summary: temporary save for backprojection
                    356: 
1.267     brouard   357:   Revision 1.266  2017/05/13 07:26:12  brouard
                    358:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    359: 
1.266     brouard   360:   Revision 1.265  2017/04/26 16:22:11  brouard
                    361:   Summary: imach 0.99r13 Some bugs fixed
                    362: 
1.265     brouard   363:   Revision 1.264  2017/04/26 06:01:29  brouard
                    364:   Summary: Labels in graphs
                    365: 
1.264     brouard   366:   Revision 1.263  2017/04/24 15:23:15  brouard
                    367:   Summary: to save
                    368: 
1.263     brouard   369:   Revision 1.262  2017/04/18 16:48:12  brouard
                    370:   *** empty log message ***
                    371: 
1.262     brouard   372:   Revision 1.261  2017/04/05 10:14:09  brouard
                    373:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    374: 
1.261     brouard   375:   Revision 1.260  2017/04/04 17:46:59  brouard
                    376:   Summary: Gnuplot indexations fixed (humm)
                    377: 
1.260     brouard   378:   Revision 1.259  2017/04/04 13:01:16  brouard
                    379:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    380: 
1.259     brouard   381:   Revision 1.258  2017/04/03 10:17:47  brouard
                    382:   Summary: Version 0.99r12
                    383: 
                    384:   Some cleanings, conformed with updated documentation.
                    385: 
1.258     brouard   386:   Revision 1.257  2017/03/29 16:53:30  brouard
                    387:   Summary: Temp
                    388: 
1.257     brouard   389:   Revision 1.256  2017/03/27 05:50:23  brouard
                    390:   Summary: Temporary
                    391: 
1.256     brouard   392:   Revision 1.255  2017/03/08 16:02:28  brouard
                    393:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    394: 
1.255     brouard   395:   Revision 1.254  2017/03/08 07:13:00  brouard
                    396:   Summary: Fixing data parameter line
                    397: 
1.254     brouard   398:   Revision 1.253  2016/12/15 11:59:41  brouard
                    399:   Summary: 0.99 in progress
                    400: 
1.253     brouard   401:   Revision 1.252  2016/09/15 21:15:37  brouard
                    402:   *** empty log message ***
                    403: 
1.252     brouard   404:   Revision 1.251  2016/09/15 15:01:13  brouard
                    405:   Summary: not working
                    406: 
1.251     brouard   407:   Revision 1.250  2016/09/08 16:07:27  brouard
                    408:   Summary: continue
                    409: 
1.250     brouard   410:   Revision 1.249  2016/09/07 17:14:18  brouard
                    411:   Summary: Starting values from frequencies
                    412: 
1.249     brouard   413:   Revision 1.248  2016/09/07 14:10:18  brouard
                    414:   *** empty log message ***
                    415: 
1.248     brouard   416:   Revision 1.247  2016/09/02 11:11:21  brouard
                    417:   *** empty log message ***
                    418: 
1.247     brouard   419:   Revision 1.246  2016/09/02 08:49:22  brouard
                    420:   *** empty log message ***
                    421: 
1.246     brouard   422:   Revision 1.245  2016/09/02 07:25:01  brouard
                    423:   *** empty log message ***
                    424: 
1.245     brouard   425:   Revision 1.244  2016/09/02 07:17:34  brouard
                    426:   *** empty log message ***
                    427: 
1.244     brouard   428:   Revision 1.243  2016/09/02 06:45:35  brouard
                    429:   *** empty log message ***
                    430: 
1.243     brouard   431:   Revision 1.242  2016/08/30 15:01:20  brouard
                    432:   Summary: Fixing a lots
                    433: 
1.242     brouard   434:   Revision 1.241  2016/08/29 17:17:25  brouard
                    435:   Summary: gnuplot problem in Back projection to fix
                    436: 
1.241     brouard   437:   Revision 1.240  2016/08/29 07:53:18  brouard
                    438:   Summary: Better
                    439: 
1.240     brouard   440:   Revision 1.239  2016/08/26 15:51:03  brouard
                    441:   Summary: Improvement in Powell output in order to copy and paste
                    442: 
                    443:   Author:
                    444: 
1.239     brouard   445:   Revision 1.238  2016/08/26 14:23:35  brouard
                    446:   Summary: Starting tests of 0.99
                    447: 
1.238     brouard   448:   Revision 1.237  2016/08/26 09:20:19  brouard
                    449:   Summary: to valgrind
                    450: 
1.237     brouard   451:   Revision 1.236  2016/08/25 10:50:18  brouard
                    452:   *** empty log message ***
                    453: 
1.236     brouard   454:   Revision 1.235  2016/08/25 06:59:23  brouard
                    455:   *** empty log message ***
                    456: 
1.235     brouard   457:   Revision 1.234  2016/08/23 16:51:20  brouard
                    458:   *** empty log message ***
                    459: 
1.234     brouard   460:   Revision 1.233  2016/08/23 07:40:50  brouard
                    461:   Summary: not working
                    462: 
1.233     brouard   463:   Revision 1.232  2016/08/22 14:20:21  brouard
                    464:   Summary: not working
                    465: 
1.232     brouard   466:   Revision 1.231  2016/08/22 07:17:15  brouard
                    467:   Summary: not working
                    468: 
1.231     brouard   469:   Revision 1.230  2016/08/22 06:55:53  brouard
                    470:   Summary: Not working
                    471: 
1.230     brouard   472:   Revision 1.229  2016/07/23 09:45:53  brouard
                    473:   Summary: Completing for func too
                    474: 
1.229     brouard   475:   Revision 1.228  2016/07/22 17:45:30  brouard
                    476:   Summary: Fixing some arrays, still debugging
                    477: 
1.227     brouard   478:   Revision 1.226  2016/07/12 18:42:34  brouard
                    479:   Summary: temp
                    480: 
1.226     brouard   481:   Revision 1.225  2016/07/12 08:40:03  brouard
                    482:   Summary: saving but not running
                    483: 
1.225     brouard   484:   Revision 1.224  2016/07/01 13:16:01  brouard
                    485:   Summary: Fixes
                    486: 
1.224     brouard   487:   Revision 1.223  2016/02/19 09:23:35  brouard
                    488:   Summary: temporary
                    489: 
1.223     brouard   490:   Revision 1.222  2016/02/17 08:14:50  brouard
                    491:   Summary: Probably last 0.98 stable version 0.98r6
                    492: 
1.222     brouard   493:   Revision 1.221  2016/02/15 23:35:36  brouard
                    494:   Summary: minor bug
                    495: 
1.220     brouard   496:   Revision 1.219  2016/02/15 00:48:12  brouard
                    497:   *** empty log message ***
                    498: 
1.219     brouard   499:   Revision 1.218  2016/02/12 11:29:23  brouard
                    500:   Summary: 0.99 Back projections
                    501: 
1.218     brouard   502:   Revision 1.217  2015/12/23 17:18:31  brouard
                    503:   Summary: Experimental backcast
                    504: 
1.217     brouard   505:   Revision 1.216  2015/12/18 17:32:11  brouard
                    506:   Summary: 0.98r4 Warning and status=-2
                    507: 
                    508:   Version 0.98r4 is now:
                    509:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    510:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    511:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    512: 
1.216     brouard   513:   Revision 1.215  2015/12/16 08:52:24  brouard
                    514:   Summary: 0.98r4 working
                    515: 
1.215     brouard   516:   Revision 1.214  2015/12/16 06:57:54  brouard
                    517:   Summary: temporary not working
                    518: 
1.214     brouard   519:   Revision 1.213  2015/12/11 18:22:17  brouard
                    520:   Summary: 0.98r4
                    521: 
1.213     brouard   522:   Revision 1.212  2015/11/21 12:47:24  brouard
                    523:   Summary: minor typo
                    524: 
1.212     brouard   525:   Revision 1.211  2015/11/21 12:41:11  brouard
                    526:   Summary: 0.98r3 with some graph of projected cross-sectional
                    527: 
                    528:   Author: Nicolas Brouard
                    529: 
1.211     brouard   530:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   531:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   532:   Summary: Adding ftolpl parameter
                    533:   Author: N Brouard
                    534: 
                    535:   We had difficulties to get smoothed confidence intervals. It was due
                    536:   to the period prevalence which wasn't computed accurately. The inner
                    537:   parameter ftolpl is now an outer parameter of the .imach parameter
                    538:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    539:   computation are long.
                    540: 
1.209     brouard   541:   Revision 1.208  2015/11/17 14:31:57  brouard
                    542:   Summary: temporary
                    543: 
1.208     brouard   544:   Revision 1.207  2015/10/27 17:36:57  brouard
                    545:   *** empty log message ***
                    546: 
1.207     brouard   547:   Revision 1.206  2015/10/24 07:14:11  brouard
                    548:   *** empty log message ***
                    549: 
1.206     brouard   550:   Revision 1.205  2015/10/23 15:50:53  brouard
                    551:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    552: 
1.205     brouard   553:   Revision 1.204  2015/10/01 16:20:26  brouard
                    554:   Summary: Some new graphs of contribution to likelihood
                    555: 
1.204     brouard   556:   Revision 1.203  2015/09/30 17:45:14  brouard
                    557:   Summary: looking at better estimation of the hessian
                    558: 
                    559:   Also a better criteria for convergence to the period prevalence And
                    560:   therefore adding the number of years needed to converge. (The
                    561:   prevalence in any alive state shold sum to one
                    562: 
1.203     brouard   563:   Revision 1.202  2015/09/22 19:45:16  brouard
                    564:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    565: 
1.202     brouard   566:   Revision 1.201  2015/09/15 17:34:58  brouard
                    567:   Summary: 0.98r0
                    568: 
                    569:   - Some new graphs like suvival functions
                    570:   - Some bugs fixed like model=1+age+V2.
                    571: 
1.201     brouard   572:   Revision 1.200  2015/09/09 16:53:55  brouard
                    573:   Summary: Big bug thanks to Flavia
                    574: 
                    575:   Even model=1+age+V2. did not work anymore
                    576: 
1.200     brouard   577:   Revision 1.199  2015/09/07 14:09:23  brouard
                    578:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    579: 
1.199     brouard   580:   Revision 1.198  2015/09/03 07:14:39  brouard
                    581:   Summary: 0.98q5 Flavia
                    582: 
1.198     brouard   583:   Revision 1.197  2015/09/01 18:24:39  brouard
                    584:   *** empty log message ***
                    585: 
1.197     brouard   586:   Revision 1.196  2015/08/18 23:17:52  brouard
                    587:   Summary: 0.98q5
                    588: 
1.196     brouard   589:   Revision 1.195  2015/08/18 16:28:39  brouard
                    590:   Summary: Adding a hack for testing purpose
                    591: 
                    592:   After reading the title, ftol and model lines, if the comment line has
                    593:   a q, starting with #q, the answer at the end of the run is quit. It
                    594:   permits to run test files in batch with ctest. The former workaround was
                    595:   $ echo q | imach foo.imach
                    596: 
1.195     brouard   597:   Revision 1.194  2015/08/18 13:32:00  brouard
                    598:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    599: 
1.194     brouard   600:   Revision 1.193  2015/08/04 07:17:42  brouard
                    601:   Summary: 0.98q4
                    602: 
1.193     brouard   603:   Revision 1.192  2015/07/16 16:49:02  brouard
                    604:   Summary: Fixing some outputs
                    605: 
1.192     brouard   606:   Revision 1.191  2015/07/14 10:00:33  brouard
                    607:   Summary: Some fixes
                    608: 
1.191     brouard   609:   Revision 1.190  2015/05/05 08:51:13  brouard
                    610:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    611: 
                    612:   Fix 1+age+.
                    613: 
1.190     brouard   614:   Revision 1.189  2015/04/30 14:45:16  brouard
                    615:   Summary: 0.98q2
                    616: 
1.189     brouard   617:   Revision 1.188  2015/04/30 08:27:53  brouard
                    618:   *** empty log message ***
                    619: 
1.188     brouard   620:   Revision 1.187  2015/04/29 09:11:15  brouard
                    621:   *** empty log message ***
                    622: 
1.187     brouard   623:   Revision 1.186  2015/04/23 12:01:52  brouard
                    624:   Summary: V1*age is working now, version 0.98q1
                    625: 
                    626:   Some codes had been disabled in order to simplify and Vn*age was
                    627:   working in the optimization phase, ie, giving correct MLE parameters,
                    628:   but, as usual, outputs were not correct and program core dumped.
                    629: 
1.186     brouard   630:   Revision 1.185  2015/03/11 13:26:42  brouard
                    631:   Summary: Inclusion of compile and links command line for Intel Compiler
                    632: 
1.185     brouard   633:   Revision 1.184  2015/03/11 11:52:39  brouard
                    634:   Summary: Back from Windows 8. Intel Compiler
                    635: 
1.184     brouard   636:   Revision 1.183  2015/03/10 20:34:32  brouard
                    637:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    638: 
                    639:   We use directest instead of original Powell test; probably no
                    640:   incidence on the results, but better justifications;
                    641:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    642:   wrong results.
                    643: 
1.183     brouard   644:   Revision 1.182  2015/02/12 08:19:57  brouard
                    645:   Summary: Trying to keep directest which seems simpler and more general
                    646:   Author: Nicolas Brouard
                    647: 
1.182     brouard   648:   Revision 1.181  2015/02/11 23:22:24  brouard
                    649:   Summary: Comments on Powell added
                    650: 
                    651:   Author:
                    652: 
1.181     brouard   653:   Revision 1.180  2015/02/11 17:33:45  brouard
                    654:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    655: 
1.180     brouard   656:   Revision 1.179  2015/01/04 09:57:06  brouard
                    657:   Summary: back to OS/X
                    658: 
1.179     brouard   659:   Revision 1.178  2015/01/04 09:35:48  brouard
                    660:   *** empty log message ***
                    661: 
1.178     brouard   662:   Revision 1.177  2015/01/03 18:40:56  brouard
                    663:   Summary: Still testing ilc32 on OSX
                    664: 
1.177     brouard   665:   Revision 1.176  2015/01/03 16:45:04  brouard
                    666:   *** empty log message ***
                    667: 
1.176     brouard   668:   Revision 1.175  2015/01/03 16:33:42  brouard
                    669:   *** empty log message ***
                    670: 
1.175     brouard   671:   Revision 1.174  2015/01/03 16:15:49  brouard
                    672:   Summary: Still in cross-compilation
                    673: 
1.174     brouard   674:   Revision 1.173  2015/01/03 12:06:26  brouard
                    675:   Summary: trying to detect cross-compilation
                    676: 
1.173     brouard   677:   Revision 1.172  2014/12/27 12:07:47  brouard
                    678:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    679: 
1.172     brouard   680:   Revision 1.171  2014/12/23 13:26:59  brouard
                    681:   Summary: Back from Visual C
                    682: 
                    683:   Still problem with utsname.h on Windows
                    684: 
1.171     brouard   685:   Revision 1.170  2014/12/23 11:17:12  brouard
                    686:   Summary: Cleaning some \%% back to %%
                    687: 
                    688:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    689: 
1.170     brouard   690:   Revision 1.169  2014/12/22 23:08:31  brouard
                    691:   Summary: 0.98p
                    692: 
                    693:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    694: 
1.169     brouard   695:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   696:   Summary: update
1.169     brouard   697: 
1.168     brouard   698:   Revision 1.167  2014/12/22 13:50:56  brouard
                    699:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    700: 
                    701:   Testing on Linux 64
                    702: 
1.167     brouard   703:   Revision 1.166  2014/12/22 11:40:47  brouard
                    704:   *** empty log message ***
                    705: 
1.166     brouard   706:   Revision 1.165  2014/12/16 11:20:36  brouard
                    707:   Summary: After compiling on Visual C
                    708: 
                    709:   * imach.c (Module): Merging 1.61 to 1.162
                    710: 
1.165     brouard   711:   Revision 1.164  2014/12/16 10:52:11  brouard
                    712:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    713: 
                    714:   * imach.c (Module): Merging 1.61 to 1.162
                    715: 
1.164     brouard   716:   Revision 1.163  2014/12/16 10:30:11  brouard
                    717:   * imach.c (Module): Merging 1.61 to 1.162
                    718: 
1.163     brouard   719:   Revision 1.162  2014/09/25 11:43:39  brouard
                    720:   Summary: temporary backup 0.99!
                    721: 
1.162     brouard   722:   Revision 1.1  2014/09/16 11:06:58  brouard
                    723:   Summary: With some code (wrong) for nlopt
                    724: 
                    725:   Author:
                    726: 
                    727:   Revision 1.161  2014/09/15 20:41:41  brouard
                    728:   Summary: Problem with macro SQR on Intel compiler
                    729: 
1.161     brouard   730:   Revision 1.160  2014/09/02 09:24:05  brouard
                    731:   *** empty log message ***
                    732: 
1.160     brouard   733:   Revision 1.159  2014/09/01 10:34:10  brouard
                    734:   Summary: WIN32
                    735:   Author: Brouard
                    736: 
1.159     brouard   737:   Revision 1.158  2014/08/27 17:11:51  brouard
                    738:   *** empty log message ***
                    739: 
1.158     brouard   740:   Revision 1.157  2014/08/27 16:26:55  brouard
                    741:   Summary: Preparing windows Visual studio version
                    742:   Author: Brouard
                    743: 
                    744:   In order to compile on Visual studio, time.h is now correct and time_t
                    745:   and tm struct should be used. difftime should be used but sometimes I
                    746:   just make the differences in raw time format (time(&now).
                    747:   Trying to suppress #ifdef LINUX
                    748:   Add xdg-open for __linux in order to open default browser.
                    749: 
1.157     brouard   750:   Revision 1.156  2014/08/25 20:10:10  brouard
                    751:   *** empty log message ***
                    752: 
1.156     brouard   753:   Revision 1.155  2014/08/25 18:32:34  brouard
                    754:   Summary: New compile, minor changes
                    755:   Author: Brouard
                    756: 
1.155     brouard   757:   Revision 1.154  2014/06/20 17:32:08  brouard
                    758:   Summary: Outputs now all graphs of convergence to period prevalence
                    759: 
1.154     brouard   760:   Revision 1.153  2014/06/20 16:45:46  brouard
                    761:   Summary: If 3 live state, convergence to period prevalence on same graph
                    762:   Author: Brouard
                    763: 
1.153     brouard   764:   Revision 1.152  2014/06/18 17:54:09  brouard
                    765:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    766: 
1.152     brouard   767:   Revision 1.151  2014/06/18 16:43:30  brouard
                    768:   *** empty log message ***
                    769: 
1.151     brouard   770:   Revision 1.150  2014/06/18 16:42:35  brouard
                    771:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    772:   Author: brouard
                    773: 
1.150     brouard   774:   Revision 1.149  2014/06/18 15:51:14  brouard
                    775:   Summary: Some fixes in parameter files errors
                    776:   Author: Nicolas Brouard
                    777: 
1.149     brouard   778:   Revision 1.148  2014/06/17 17:38:48  brouard
                    779:   Summary: Nothing new
                    780:   Author: Brouard
                    781: 
                    782:   Just a new packaging for OS/X version 0.98nS
                    783: 
1.148     brouard   784:   Revision 1.147  2014/06/16 10:33:11  brouard
                    785:   *** empty log message ***
                    786: 
1.147     brouard   787:   Revision 1.146  2014/06/16 10:20:28  brouard
                    788:   Summary: Merge
                    789:   Author: Brouard
                    790: 
                    791:   Merge, before building revised version.
                    792: 
1.146     brouard   793:   Revision 1.145  2014/06/10 21:23:15  brouard
                    794:   Summary: Debugging with valgrind
                    795:   Author: Nicolas Brouard
                    796: 
                    797:   Lot of changes in order to output the results with some covariates
                    798:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    799:   improve the code.
                    800:   No more memory valgrind error but a lot has to be done in order to
                    801:   continue the work of splitting the code into subroutines.
                    802:   Also, decodemodel has been improved. Tricode is still not
                    803:   optimal. nbcode should be improved. Documentation has been added in
                    804:   the source code.
                    805: 
1.144     brouard   806:   Revision 1.143  2014/01/26 09:45:38  brouard
                    807:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    808: 
                    809:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    810:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    811: 
1.143     brouard   812:   Revision 1.142  2014/01/26 03:57:36  brouard
                    813:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    814: 
                    815:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    816: 
1.142     brouard   817:   Revision 1.141  2014/01/26 02:42:01  brouard
                    818:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    819: 
1.141     brouard   820:   Revision 1.140  2011/09/02 10:37:54  brouard
                    821:   Summary: times.h is ok with mingw32 now.
                    822: 
1.140     brouard   823:   Revision 1.139  2010/06/14 07:50:17  brouard
                    824:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    825:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    826: 
1.139     brouard   827:   Revision 1.138  2010/04/30 18:19:40  brouard
                    828:   *** empty log message ***
                    829: 
1.138     brouard   830:   Revision 1.137  2010/04/29 18:11:38  brouard
                    831:   (Module): Checking covariates for more complex models
                    832:   than V1+V2. A lot of change to be done. Unstable.
                    833: 
1.137     brouard   834:   Revision 1.136  2010/04/26 20:30:53  brouard
                    835:   (Module): merging some libgsl code. Fixing computation
                    836:   of likelione (using inter/intrapolation if mle = 0) in order to
                    837:   get same likelihood as if mle=1.
                    838:   Some cleaning of code and comments added.
                    839: 
1.136     brouard   840:   Revision 1.135  2009/10/29 15:33:14  brouard
                    841:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    842: 
1.135     brouard   843:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   846:   Revision 1.133  2009/07/06 10:21:25  brouard
                    847:   just nforces
                    848: 
1.133     brouard   849:   Revision 1.132  2009/07/06 08:22:05  brouard
                    850:   Many tings
                    851: 
1.132     brouard   852:   Revision 1.131  2009/06/20 16:22:47  brouard
                    853:   Some dimensions resccaled
                    854: 
1.131     brouard   855:   Revision 1.130  2009/05/26 06:44:34  brouard
                    856:   (Module): Max Covariate is now set to 20 instead of 8. A
                    857:   lot of cleaning with variables initialized to 0. Trying to make
                    858:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    859: 
1.130     brouard   860:   Revision 1.129  2007/08/31 13:49:27  lievre
                    861:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    862: 
1.129     lievre    863:   Revision 1.128  2006/06/30 13:02:05  brouard
                    864:   (Module): Clarifications on computing e.j
                    865: 
1.128     brouard   866:   Revision 1.127  2006/04/28 18:11:50  brouard
                    867:   (Module): Yes the sum of survivors was wrong since
                    868:   imach-114 because nhstepm was no more computed in the age
                    869:   loop. Now we define nhstepma in the age loop.
                    870:   (Module): In order to speed up (in case of numerous covariates) we
                    871:   compute health expectancies (without variances) in a first step
                    872:   and then all the health expectancies with variances or standard
                    873:   deviation (needs data from the Hessian matrices) which slows the
                    874:   computation.
                    875:   In the future we should be able to stop the program is only health
                    876:   expectancies and graph are needed without standard deviations.
                    877: 
1.127     brouard   878:   Revision 1.126  2006/04/28 17:23:28  brouard
                    879:   (Module): Yes the sum of survivors was wrong since
                    880:   imach-114 because nhstepm was no more computed in the age
                    881:   loop. Now we define nhstepma in the age loop.
                    882:   Version 0.98h
                    883: 
1.126     brouard   884:   Revision 1.125  2006/04/04 15:20:31  lievre
                    885:   Errors in calculation of health expectancies. Age was not initialized.
                    886:   Forecasting file added.
                    887: 
                    888:   Revision 1.124  2006/03/22 17:13:53  lievre
                    889:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    890:   The log-likelihood is printed in the log file
                    891: 
                    892:   Revision 1.123  2006/03/20 10:52:43  brouard
                    893:   * imach.c (Module): <title> changed, corresponds to .htm file
                    894:   name. <head> headers where missing.
                    895: 
                    896:   * imach.c (Module): Weights can have a decimal point as for
                    897:   English (a comma might work with a correct LC_NUMERIC environment,
                    898:   otherwise the weight is truncated).
                    899:   Modification of warning when the covariates values are not 0 or
                    900:   1.
                    901:   Version 0.98g
                    902: 
                    903:   Revision 1.122  2006/03/20 09:45:41  brouard
                    904:   (Module): Weights can have a decimal point as for
                    905:   English (a comma might work with a correct LC_NUMERIC environment,
                    906:   otherwise the weight is truncated).
                    907:   Modification of warning when the covariates values are not 0 or
                    908:   1.
                    909:   Version 0.98g
                    910: 
                    911:   Revision 1.121  2006/03/16 17:45:01  lievre
                    912:   * imach.c (Module): Comments concerning covariates added
                    913: 
                    914:   * imach.c (Module): refinements in the computation of lli if
                    915:   status=-2 in order to have more reliable computation if stepm is
                    916:   not 1 month. Version 0.98f
                    917: 
                    918:   Revision 1.120  2006/03/16 15:10:38  lievre
                    919:   (Module): refinements in the computation of lli if
                    920:   status=-2 in order to have more reliable computation if stepm is
                    921:   not 1 month. Version 0.98f
                    922: 
                    923:   Revision 1.119  2006/03/15 17:42:26  brouard
                    924:   (Module): Bug if status = -2, the loglikelihood was
                    925:   computed as likelihood omitting the logarithm. Version O.98e
                    926: 
                    927:   Revision 1.118  2006/03/14 18:20:07  brouard
                    928:   (Module): varevsij Comments added explaining the second
                    929:   table of variances if popbased=1 .
                    930:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    931:   (Module): Function pstamp added
                    932:   (Module): Version 0.98d
                    933: 
                    934:   Revision 1.117  2006/03/14 17:16:22  brouard
                    935:   (Module): varevsij Comments added explaining the second
                    936:   table of variances if popbased=1 .
                    937:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    938:   (Module): Function pstamp added
                    939:   (Module): Version 0.98d
                    940: 
                    941:   Revision 1.116  2006/03/06 10:29:27  brouard
                    942:   (Module): Variance-covariance wrong links and
                    943:   varian-covariance of ej. is needed (Saito).
                    944: 
                    945:   Revision 1.115  2006/02/27 12:17:45  brouard
                    946:   (Module): One freematrix added in mlikeli! 0.98c
                    947: 
                    948:   Revision 1.114  2006/02/26 12:57:58  brouard
                    949:   (Module): Some improvements in processing parameter
                    950:   filename with strsep.
                    951: 
                    952:   Revision 1.113  2006/02/24 14:20:24  brouard
                    953:   (Module): Memory leaks checks with valgrind and:
                    954:   datafile was not closed, some imatrix were not freed and on matrix
                    955:   allocation too.
                    956: 
                    957:   Revision 1.112  2006/01/30 09:55:26  brouard
                    958:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    959: 
                    960:   Revision 1.111  2006/01/25 20:38:18  brouard
                    961:   (Module): Lots of cleaning and bugs added (Gompertz)
                    962:   (Module): Comments can be added in data file. Missing date values
                    963:   can be a simple dot '.'.
                    964: 
                    965:   Revision 1.110  2006/01/25 00:51:50  brouard
                    966:   (Module): Lots of cleaning and bugs added (Gompertz)
                    967: 
                    968:   Revision 1.109  2006/01/24 19:37:15  brouard
                    969:   (Module): Comments (lines starting with a #) are allowed in data.
                    970: 
                    971:   Revision 1.108  2006/01/19 18:05:42  lievre
                    972:   Gnuplot problem appeared...
                    973:   To be fixed
                    974: 
                    975:   Revision 1.107  2006/01/19 16:20:37  brouard
                    976:   Test existence of gnuplot in imach path
                    977: 
                    978:   Revision 1.106  2006/01/19 13:24:36  brouard
                    979:   Some cleaning and links added in html output
                    980: 
                    981:   Revision 1.105  2006/01/05 20:23:19  lievre
                    982:   *** empty log message ***
                    983: 
                    984:   Revision 1.104  2005/09/30 16:11:43  lievre
                    985:   (Module): sump fixed, loop imx fixed, and simplifications.
                    986:   (Module): If the status is missing at the last wave but we know
                    987:   that the person is alive, then we can code his/her status as -2
                    988:   (instead of missing=-1 in earlier versions) and his/her
                    989:   contributions to the likelihood is 1 - Prob of dying from last
                    990:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    991:   the healthy state at last known wave). Version is 0.98
                    992: 
                    993:   Revision 1.103  2005/09/30 15:54:49  lievre
                    994:   (Module): sump fixed, loop imx fixed, and simplifications.
                    995: 
                    996:   Revision 1.102  2004/09/15 17:31:30  brouard
                    997:   Add the possibility to read data file including tab characters.
                    998: 
                    999:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1000:   Fix on curr_time
                   1001: 
                   1002:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1003:   Add version for Mac OS X. Just define UNIX in Makefile
                   1004: 
                   1005:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1006:   *** empty log message ***
                   1007: 
                   1008:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1009:   New version 0.97 . First attempt to estimate force of mortality
                   1010:   directly from the data i.e. without the need of knowing the health
                   1011:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1012:   This is the basic analysis of mortality and should be done before any
                   1013:   other analysis, in order to test if the mortality estimated from the
                   1014:   cross-longitudinal survey is different from the mortality estimated
                   1015:   from other sources like vital statistic data.
                   1016: 
                   1017:   The same imach parameter file can be used but the option for mle should be -3.
                   1018: 
1.324     brouard  1019:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1020:   former routines in order to include the new code within the former code.
                   1021: 
                   1022:   The output is very simple: only an estimate of the intercept and of
                   1023:   the slope with 95% confident intervals.
                   1024: 
                   1025:   Current limitations:
                   1026:   A) Even if you enter covariates, i.e. with the
                   1027:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1028:   B) There is no computation of Life Expectancy nor Life Table.
                   1029: 
                   1030:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1031:   Version 0.96d. Population forecasting command line is (temporarily)
                   1032:   suppressed.
                   1033: 
                   1034:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1035:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1036:   rewritten within the same printf. Workaround: many printfs.
                   1037: 
                   1038:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1039:   * imach.c (Repository):
                   1040:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1041:   matrix (cov(a12,c31) instead of numbers.
                   1042: 
                   1043:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1044:   Just cleaning
                   1045: 
                   1046:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1047:   (Module): On windows (cygwin) function asctime_r doesn't
                   1048:   exist so I changed back to asctime which exists.
                   1049:   (Module): Version 0.96b
                   1050: 
                   1051:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1052:   (Module): On windows (cygwin) function asctime_r doesn't
                   1053:   exist so I changed back to asctime which exists.
                   1054: 
                   1055:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1056:   * imach.c (Repository): Duplicated warning errors corrected.
                   1057:   (Repository): Elapsed time after each iteration is now output. It
                   1058:   helps to forecast when convergence will be reached. Elapsed time
                   1059:   is stamped in powell.  We created a new html file for the graphs
                   1060:   concerning matrix of covariance. It has extension -cov.htm.
                   1061: 
                   1062:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1063:   (Module): Some bugs corrected for windows. Also, when
                   1064:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1065:   of the covariance matrix to be input.
                   1066: 
                   1067:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1068:   (Module): Some bugs corrected for windows. Also, when
                   1069:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1070:   of the covariance matrix to be input.
                   1071: 
                   1072:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1073:   * 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.
                   1074: 
                   1075:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1076:   Version 0.96
                   1077: 
                   1078:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1079:   (Module): Change position of html and gnuplot routines and added
                   1080:   routine fileappend.
                   1081: 
                   1082:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1083:   * imach.c (Repository): Check when date of death was earlier that
                   1084:   current date of interview. It may happen when the death was just
                   1085:   prior to the death. In this case, dh was negative and likelihood
                   1086:   was wrong (infinity). We still send an "Error" but patch by
                   1087:   assuming that the date of death was just one stepm after the
                   1088:   interview.
                   1089:   (Repository): Because some people have very long ID (first column)
                   1090:   we changed int to long in num[] and we added a new lvector for
                   1091:   memory allocation. But we also truncated to 8 characters (left
                   1092:   truncation)
                   1093:   (Repository): No more line truncation errors.
                   1094: 
                   1095:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1096:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1097:   place. It differs from routine "prevalence" which may be called
                   1098:   many times. Probs is memory consuming and must be used with
                   1099:   parcimony.
                   1100:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1101: 
                   1102:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1103:   *** empty log message ***
                   1104: 
                   1105:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1106:   Add log in  imach.c and  fullversion number is now printed.
                   1107: 
                   1108: */
                   1109: /*
                   1110:    Interpolated Markov Chain
                   1111: 
                   1112:   Short summary of the programme:
                   1113:   
1.227     brouard  1114:   This program computes Healthy Life Expectancies or State-specific
                   1115:   (if states aren't health statuses) Expectancies from
                   1116:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1117: 
                   1118:   -1- a first survey ("cross") where individuals from different ages
                   1119:   are interviewed on their health status or degree of disability (in
                   1120:   the case of a health survey which is our main interest)
                   1121: 
                   1122:   -2- at least a second wave of interviews ("longitudinal") which
                   1123:   measure each change (if any) in individual health status.  Health
                   1124:   expectancies are computed from the time spent in each health state
                   1125:   according to a model. More health states you consider, more time is
                   1126:   necessary to reach the Maximum Likelihood of the parameters involved
                   1127:   in the model.  The simplest model is the multinomial logistic model
                   1128:   where pij is the probability to be observed in state j at the second
                   1129:   wave conditional to be observed in state i at the first
                   1130:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1131:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1132:   have a more complex model than "constant and age", you should modify
                   1133:   the program where the markup *Covariates have to be included here
                   1134:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1135:   convergence.
                   1136: 
                   1137:   The advantage of this computer programme, compared to a simple
                   1138:   multinomial logistic model, is clear when the delay between waves is not
                   1139:   identical for each individual. Also, if a individual missed an
                   1140:   intermediate interview, the information is lost, but taken into
                   1141:   account using an interpolation or extrapolation.  
                   1142: 
                   1143:   hPijx is the probability to be observed in state i at age x+h
                   1144:   conditional to the observed state i at age x. The delay 'h' can be
                   1145:   split into an exact number (nh*stepm) of unobserved intermediate
                   1146:   states. This elementary transition (by month, quarter,
                   1147:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1148:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1149:   and the contribution of each individual to the likelihood is simply
                   1150:   hPijx.
                   1151: 
                   1152:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1153:   of the life expectancies. It also computes the period (stable) prevalence.
                   1154: 
                   1155: Back prevalence and projections:
1.227     brouard  1156: 
                   1157:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1158:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1159:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1160:    mobilavproj)
                   1161: 
                   1162:     Computes the back prevalence limit for any combination of
                   1163:     covariate values k at any age between ageminpar and agemaxpar and
                   1164:     returns it in **bprlim. In the loops,
                   1165: 
                   1166:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1167:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1168: 
                   1169:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1170:    Computes for any combination of covariates k and any age between bage and fage 
                   1171:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1172:                        oldm=oldms;savm=savms;
1.227     brouard  1173: 
1.267     brouard  1174:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1175:      Computes the transition matrix starting at age 'age' over
                   1176:      'nhstepm*hstepm*stepm' months (i.e. until
                   1177:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1178:      nhstepm*hstepm matrices. 
                   1179: 
                   1180:      Returns p3mat[i][j][h] after calling
                   1181:      p3mat[i][j][h]=matprod2(newm,
                   1182:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1183:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1184:      oldm);
1.226     brouard  1185: 
                   1186: Important routines
                   1187: 
                   1188: - func (or funcone), computes logit (pij) distinguishing
                   1189:   o fixed variables (single or product dummies or quantitative);
                   1190:   o varying variables by:
                   1191:    (1) wave (single, product dummies, quantitative), 
                   1192:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1193:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1194:        % varying dummy (not done) or quantitative (not done);
                   1195: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1196:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1197: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1198:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1199:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1200: 
1.226     brouard  1201: 
                   1202:   
1.324     brouard  1203:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1204:            Institut national d'études démographiques, Paris.
1.126     brouard  1205:   This software have been partly granted by Euro-REVES, a concerted action
                   1206:   from the European Union.
                   1207:   It is copyrighted identically to a GNU software product, ie programme and
                   1208:   software can be distributed freely for non commercial use. Latest version
                   1209:   can be accessed at http://euroreves.ined.fr/imach .
                   1210: 
                   1211:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1212:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1213:   
                   1214:   **********************************************************************/
                   1215: /*
                   1216:   main
                   1217:   read parameterfile
                   1218:   read datafile
                   1219:   concatwav
                   1220:   freqsummary
                   1221:   if (mle >= 1)
                   1222:     mlikeli
                   1223:   print results files
                   1224:   if mle==1 
                   1225:      computes hessian
                   1226:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1227:       begin-prev-date,...
                   1228:   open gnuplot file
                   1229:   open html file
1.145     brouard  1230:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1231:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1232:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1233:     freexexit2 possible for memory heap.
                   1234: 
                   1235:   h Pij x                         | pij_nom  ficrestpij
                   1236:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1237:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1238:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1239: 
                   1240:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1241:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1242:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1243:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1244:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1245: 
1.126     brouard  1246:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1247:   health expectancies
                   1248:   Variance-covariance of DFLE
                   1249:   prevalence()
                   1250:    movingaverage()
                   1251:   varevsij() 
                   1252:   if popbased==1 varevsij(,popbased)
                   1253:   total life expectancies
                   1254:   Variance of period (stable) prevalence
                   1255:  end
                   1256: */
                   1257: 
1.187     brouard  1258: /* #define DEBUG */
                   1259: /* #define DEBUGBRENT */
1.203     brouard  1260: /* #define DEBUGLINMIN */
                   1261: /* #define DEBUGHESS */
                   1262: #define DEBUGHESSIJ
1.224     brouard  1263: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1264: #define POWELL /* Instead of NLOPT */
1.224     brouard  1265: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1266: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1267: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1268: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1269: 
                   1270: #include <math.h>
                   1271: #include <stdio.h>
                   1272: #include <stdlib.h>
                   1273: #include <string.h>
1.226     brouard  1274: #include <ctype.h>
1.159     brouard  1275: 
                   1276: #ifdef _WIN32
                   1277: #include <io.h>
1.172     brouard  1278: #include <windows.h>
                   1279: #include <tchar.h>
1.159     brouard  1280: #else
1.126     brouard  1281: #include <unistd.h>
1.159     brouard  1282: #endif
1.126     brouard  1283: 
                   1284: #include <limits.h>
                   1285: #include <sys/types.h>
1.171     brouard  1286: 
                   1287: #if defined(__GNUC__)
                   1288: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1289: #endif
                   1290: 
1.126     brouard  1291: #include <sys/stat.h>
                   1292: #include <errno.h>
1.159     brouard  1293: /* extern int errno; */
1.126     brouard  1294: 
1.157     brouard  1295: /* #ifdef LINUX */
                   1296: /* #include <time.h> */
                   1297: /* #include "timeval.h" */
                   1298: /* #else */
                   1299: /* #include <sys/time.h> */
                   1300: /* #endif */
                   1301: 
1.126     brouard  1302: #include <time.h>
                   1303: 
1.136     brouard  1304: #ifdef GSL
                   1305: #include <gsl/gsl_errno.h>
                   1306: #include <gsl/gsl_multimin.h>
                   1307: #endif
                   1308: 
1.167     brouard  1309: 
1.162     brouard  1310: #ifdef NLOPT
                   1311: #include <nlopt.h>
                   1312: typedef struct {
                   1313:   double (* function)(double [] );
                   1314: } myfunc_data ;
                   1315: #endif
                   1316: 
1.126     brouard  1317: /* #include <libintl.h> */
                   1318: /* #define _(String) gettext (String) */
                   1319: 
1.349     brouard  1320: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1321: 
                   1322: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1323: #define GNUPLOTVERSION 5.1
                   1324: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1325: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1326: #define FILENAMELENGTH 256
1.126     brouard  1327: 
                   1328: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1329: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1330: 
1.349     brouard  1331: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1332: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1333: 
                   1334: #define NINTERVMAX 8
1.144     brouard  1335: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1336: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1337: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1338: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1339: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1340: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1341: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1342: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1343: /* #define AGESUP 130 */
1.288     brouard  1344: /* #define AGESUP 150 */
                   1345: #define AGESUP 200
1.268     brouard  1346: #define AGEINF 0
1.218     brouard  1347: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1348: #define AGEBASE 40
1.194     brouard  1349: #define AGEOVERFLOW 1.e20
1.164     brouard  1350: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1351: #ifdef _WIN32
                   1352: #define DIRSEPARATOR '\\'
                   1353: #define CHARSEPARATOR "\\"
                   1354: #define ODIRSEPARATOR '/'
                   1355: #else
1.126     brouard  1356: #define DIRSEPARATOR '/'
                   1357: #define CHARSEPARATOR "/"
                   1358: #define ODIRSEPARATOR '\\'
                   1359: #endif
                   1360: 
1.350   ! brouard  1361: /* $Id: imach.c,v 1.349 2023/01/31 09:19:37 brouard Exp $ */
1.126     brouard  1362: /* $State: Exp $ */
1.196     brouard  1363: #include "version.h"
                   1364: char version[]=__IMACH_VERSION__;
1.349     brouard  1365: 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.350   ! brouard  1366: char fullversion[]="$Revision: 1.349 $ $Date: 2023/01/31 09:19:37 $"; 
1.126     brouard  1367: char strstart[80];
                   1368: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1369: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1370: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1371: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1372: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1373: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1374: 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  1375: 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  1376: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1377: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1378: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1379: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1380: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1381: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1382: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1383: 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  1384: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1385: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1386: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1387: 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 */
                   1388: 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 */
                   1389: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1390: 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  1391: int nsd=0; /**< Total number of single dummy variables (output) */
                   1392: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1393: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1394: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1395: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1396: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1397: int cptcov=0; /* Working variable */
1.334     brouard  1398: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1399: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1400: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1401: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1402: int nlstate=2; /* Number of live states */
                   1403: int ndeath=1; /* Number of dead states */
1.130     brouard  1404: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1405: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1406: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1407: int popbased=0;
                   1408: 
                   1409: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1410: int maxwav=0; /* Maxim number of waves */
                   1411: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1412: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1413: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1414:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1415: int mle=1, weightopt=0;
1.126     brouard  1416: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1417: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1418: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1419:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1420: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1421: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1422: 
1.130     brouard  1423: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1424: double **matprod2(); /* test */
1.126     brouard  1425: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1426: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1427: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1428: 
1.136     brouard  1429: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1430: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1431: FILE *ficlog, *ficrespow;
1.130     brouard  1432: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1433: double fretone; /* Only one call to likelihood */
1.130     brouard  1434: long ipmx=0; /* Number of contributions */
1.126     brouard  1435: double sw; /* Sum of weights */
                   1436: char filerespow[FILENAMELENGTH];
                   1437: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1438: FILE *ficresilk;
                   1439: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1440: FILE *ficresprobmorprev;
                   1441: FILE *fichtm, *fichtmcov; /* Html File */
                   1442: FILE *ficreseij;
                   1443: char filerese[FILENAMELENGTH];
                   1444: FILE *ficresstdeij;
                   1445: char fileresstde[FILENAMELENGTH];
                   1446: FILE *ficrescveij;
                   1447: char filerescve[FILENAMELENGTH];
                   1448: FILE  *ficresvij;
                   1449: char fileresv[FILENAMELENGTH];
1.269     brouard  1450: 
1.126     brouard  1451: char title[MAXLINE];
1.234     brouard  1452: char model[MAXLINE]; /**< The model line */
1.217     brouard  1453: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1454: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1455: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1456: char command[FILENAMELENGTH];
                   1457: int  outcmd=0;
                   1458: 
1.217     brouard  1459: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1460: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1461: char filelog[FILENAMELENGTH]; /* Log file */
                   1462: char filerest[FILENAMELENGTH];
                   1463: char fileregp[FILENAMELENGTH];
                   1464: char popfile[FILENAMELENGTH];
                   1465: 
                   1466: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1467: 
1.157     brouard  1468: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1469: /* struct timezone tzp; */
                   1470: /* extern int gettimeofday(); */
                   1471: struct tm tml, *gmtime(), *localtime();
                   1472: 
                   1473: extern time_t time();
                   1474: 
                   1475: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1476: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1477: time_t   rlast_btime; /* raw time */
1.157     brouard  1478: struct tm tm;
                   1479: 
1.126     brouard  1480: char strcurr[80], strfor[80];
                   1481: 
                   1482: char *endptr;
                   1483: long lval;
                   1484: double dval;
                   1485: 
                   1486: #define NR_END 1
                   1487: #define FREE_ARG char*
                   1488: #define FTOL 1.0e-10
                   1489: 
                   1490: #define NRANSI 
1.240     brouard  1491: #define ITMAX 200
                   1492: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1493: 
                   1494: #define TOL 2.0e-4 
                   1495: 
                   1496: #define CGOLD 0.3819660 
                   1497: #define ZEPS 1.0e-10 
                   1498: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1499: 
                   1500: #define GOLD 1.618034 
                   1501: #define GLIMIT 100.0 
                   1502: #define TINY 1.0e-20 
                   1503: 
                   1504: static double maxarg1,maxarg2;
                   1505: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1506: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1507:   
                   1508: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1509: #define rint(a) floor(a+0.5)
1.166     brouard  1510: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1511: #define mytinydouble 1.0e-16
1.166     brouard  1512: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1513: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1514: /* static double dsqrarg; */
                   1515: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1516: static double sqrarg;
                   1517: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1518: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1519: int agegomp= AGEGOMP;
                   1520: 
                   1521: int imx; 
                   1522: int stepm=1;
                   1523: /* Stepm, step in month: minimum step interpolation*/
                   1524: 
                   1525: int estepm;
                   1526: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1527: 
                   1528: int m,nb;
                   1529: long *num;
1.197     brouard  1530: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1531: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1532:                   covariate for which somebody answered excluding 
                   1533:                   undefined. Usually 2: 0 and 1. */
                   1534: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1535:                             covariate for which somebody answered including 
                   1536:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1537: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1538: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1539: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1540: 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  1541: double *ageexmed,*agecens;
                   1542: double dateintmean=0;
1.296     brouard  1543:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1544:   double anprojf, mprojf, jprojf;
1.126     brouard  1545: 
1.296     brouard  1546:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1547:   double anbackf, mbackf, jbackf;
                   1548:   double jintmean,mintmean,aintmean;  
1.126     brouard  1549: double *weight;
                   1550: int **s; /* Status */
1.141     brouard  1551: double *agedc;
1.145     brouard  1552: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1553:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1554:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1555: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1556: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1557: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1558: double  idx; 
                   1559: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1560: /* Some documentation */
                   1561:       /*   Design original data
                   1562:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1563:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1564:        *                                                             ntv=3     nqtv=1
1.330     brouard  1565:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1566:        * For time varying covariate, quanti or dummies
                   1567:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1568:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1569:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1570:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1571:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1572:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1573:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1574:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1575:        */
                   1576: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1577: /* 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
                   1578:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1579:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1580: */
1.349     brouard  1581: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1582: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1583: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1584:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1585:                                                                /* product without age, 3 for age and double product   */
                   1586: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1587:                                                                 /*(single or product without age), 2 dummy*/
                   1588:                                                                /* with age product, 3 quant with age product*/
                   1589: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1590: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1591: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1592: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1593: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1594: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1595: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1596: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1597: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1598: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1599: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1600: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350   ! brouard  1601: /* 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"*/
        !          1602: /*  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}*/
        !          1603: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>}
        !          1604: /* 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}*/
        !          1605: /* 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  1606: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1607: /* 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  1608: /* 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  1609: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1610: /* Type                    */
                   1611: /* V         1  2  3  4  5 */
                   1612: /*           F  F  V  V  V */
                   1613: /*           D  Q  D  D  Q */
                   1614: /*                         */
                   1615: int *TvarsD;
1.330     brouard  1616: int *TnsdVar;
1.234     brouard  1617: int *TvarsDind;
                   1618: int *TvarsQ;
                   1619: int *TvarsQind;
                   1620: 
1.318     brouard  1621: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1622: int nresult=0;
1.258     brouard  1623: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1624: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1625: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1626: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1627: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1628: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1629: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1630: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1631: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1632: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1633: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1634: 
                   1635: /* 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
                   1636:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1637:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1638: */
1.234     brouard  1639: /* 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  1640: 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 */
                   1641: 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 */
                   1642: 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 */
                   1643: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1644: 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 */
                   1645: 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  1646: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1647: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1648: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1649: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1650: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1651: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1652: 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 */
                   1653: 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  1654: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1655: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1656: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1657: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1658: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1659: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1660:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1661:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1662:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1663:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1664:       /* 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  1665: int *Tvarsel; /**< Selected covariates for output */
                   1666: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1667: 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  1668: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1669: 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  1670: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1671: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1672: int *Tage;
1.227     brouard  1673: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1674: 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  1675: 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*/ 
                   1676: 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  1677: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1678: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1679: int **Tvard;
1.330     brouard  1680: int **Tvardk;
1.227     brouard  1681: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1682: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1683: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1684:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1685:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1686: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1687: double *lsurv, *lpop, *tpop;
                   1688: 
1.231     brouard  1689: #define FD 1; /* Fixed dummy covariate */
                   1690: #define FQ 2; /* Fixed quantitative covariate */
                   1691: #define FP 3; /* Fixed product covariate */
                   1692: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1693: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1694: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1695: #define VD 10; /* Varying dummy covariate */
                   1696: #define VQ 11; /* Varying quantitative covariate */
                   1697: #define VP 12; /* Varying product covariate */
                   1698: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1699: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1700: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1701: #define APFD 16; /* Age product * fixed dummy covariate */
                   1702: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1703: #define APVD 18; /* Age product * varying dummy covariate */
                   1704: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1705: 
                   1706: #define FTYPE 1; /* Fixed covariate */
                   1707: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1708: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1709: 
                   1710: struct kmodel{
                   1711:        int maintype; /* main type */
                   1712:        int subtype; /* subtype */
                   1713: };
                   1714: struct kmodel modell[NCOVMAX];
                   1715: 
1.143     brouard  1716: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1717: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1718: 
                   1719: /**************** split *************************/
                   1720: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1721: {
                   1722:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1723:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1724:   */ 
                   1725:   char *ss;                            /* pointer */
1.186     brouard  1726:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1727: 
                   1728:   l1 = strlen(path );                  /* length of path */
                   1729:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1730:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1731:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1732:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1733:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1734:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1735:     /* get current working directory */
                   1736:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1737: #ifdef WIN32
                   1738:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1739: #else
                   1740:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1741: #endif
1.126     brouard  1742:       return( GLOCK_ERROR_GETCWD );
                   1743:     }
                   1744:     /* got dirc from getcwd*/
                   1745:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1746:   } else {                             /* strip directory from path */
1.126     brouard  1747:     ss++;                              /* after this, the filename */
                   1748:     l2 = strlen( ss );                 /* length of filename */
                   1749:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1750:     strcpy( name, ss );                /* save file name */
                   1751:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1752:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1753:     printf(" DIRC2 = %s \n",dirc);
                   1754:   }
                   1755:   /* We add a separator at the end of dirc if not exists */
                   1756:   l1 = strlen( dirc );                 /* length of directory */
                   1757:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1758:     dirc[l1] =  DIRSEPARATOR;
                   1759:     dirc[l1+1] = 0; 
                   1760:     printf(" DIRC3 = %s \n",dirc);
                   1761:   }
                   1762:   ss = strrchr( name, '.' );           /* find last / */
                   1763:   if (ss >0){
                   1764:     ss++;
                   1765:     strcpy(ext,ss);                    /* save extension */
                   1766:     l1= strlen( name);
                   1767:     l2= strlen(ss)+1;
                   1768:     strncpy( finame, name, l1-l2);
                   1769:     finame[l1-l2]= 0;
                   1770:   }
                   1771: 
                   1772:   return( 0 );                         /* we're done */
                   1773: }
                   1774: 
                   1775: 
                   1776: /******************************************/
                   1777: 
                   1778: void replace_back_to_slash(char *s, char*t)
                   1779: {
                   1780:   int i;
                   1781:   int lg=0;
                   1782:   i=0;
                   1783:   lg=strlen(t);
                   1784:   for(i=0; i<= lg; i++) {
                   1785:     (s[i] = t[i]);
                   1786:     if (t[i]== '\\') s[i]='/';
                   1787:   }
                   1788: }
                   1789: 
1.132     brouard  1790: char *trimbb(char *out, char *in)
1.137     brouard  1791: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1792:   char *s;
                   1793:   s=out;
                   1794:   while (*in != '\0'){
1.137     brouard  1795:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1796:       in++;
                   1797:     }
                   1798:     *out++ = *in++;
                   1799:   }
                   1800:   *out='\0';
                   1801:   return s;
                   1802: }
                   1803: 
1.187     brouard  1804: /* char *substrchaine(char *out, char *in, char *chain) */
                   1805: /* { */
                   1806: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1807: /*   char *s, *t; */
                   1808: /*   t=in;s=out; */
                   1809: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1810: /*     *out++ = *in++; */
                   1811: /*   } */
                   1812: 
                   1813: /*   /\* *in matches *chain *\/ */
                   1814: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1815: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1816: /*   } */
                   1817: /*   in--; chain--; */
                   1818: /*   while ( (*in != '\0')){ */
                   1819: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1820: /*     *out++ = *in++; */
                   1821: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1822: /*   } */
                   1823: /*   *out='\0'; */
                   1824: /*   out=s; */
                   1825: /*   return out; */
                   1826: /* } */
                   1827: char *substrchaine(char *out, char *in, char *chain)
                   1828: {
                   1829:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1830:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1831: 
                   1832:   char *strloc;
                   1833: 
1.349     brouard  1834:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1835:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1836:   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  1837:   if(strloc != NULL){ 
1.349     brouard  1838:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1839:     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)*/
                   1840:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1841:   }
1.349     brouard  1842:   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  1843:   return out;
                   1844: }
                   1845: 
                   1846: 
1.145     brouard  1847: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1848: {
1.187     brouard  1849:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1850:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1851:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1852:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1853:   */
1.160     brouard  1854:   char *s, *t;
1.145     brouard  1855:   t=in;s=in;
                   1856:   while ((*in != occ) && (*in != '\0')){
                   1857:     *alocc++ = *in++;
                   1858:   }
                   1859:   if( *in == occ){
                   1860:     *(alocc)='\0';
                   1861:     s=++in;
                   1862:   }
                   1863:  
                   1864:   if (s == t) {/* occ not found */
                   1865:     *(alocc-(in-s))='\0';
                   1866:     in=s;
                   1867:   }
                   1868:   while ( *in != '\0'){
                   1869:     *blocc++ = *in++;
                   1870:   }
                   1871: 
                   1872:   *blocc='\0';
                   1873:   return t;
                   1874: }
1.137     brouard  1875: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1876: {
1.187     brouard  1877:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1878:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1879:      gives blocc="abcdef2ghi" and alocc="j".
                   1880:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1881:   */
                   1882:   char *s, *t;
                   1883:   t=in;s=in;
                   1884:   while (*in != '\0'){
                   1885:     while( *in == occ){
                   1886:       *blocc++ = *in++;
                   1887:       s=in;
                   1888:     }
                   1889:     *blocc++ = *in++;
                   1890:   }
                   1891:   if (s == t) /* occ not found */
                   1892:     *(blocc-(in-s))='\0';
                   1893:   else
                   1894:     *(blocc-(in-s)-1)='\0';
                   1895:   in=s;
                   1896:   while ( *in != '\0'){
                   1897:     *alocc++ = *in++;
                   1898:   }
                   1899: 
                   1900:   *alocc='\0';
                   1901:   return s;
                   1902: }
                   1903: 
1.126     brouard  1904: int nbocc(char *s, char occ)
                   1905: {
                   1906:   int i,j=0;
                   1907:   int lg=20;
                   1908:   i=0;
                   1909:   lg=strlen(s);
                   1910:   for(i=0; i<= lg; i++) {
1.234     brouard  1911:     if  (s[i] == occ ) j++;
1.126     brouard  1912:   }
                   1913:   return j;
                   1914: }
                   1915: 
1.349     brouard  1916: int nboccstr(char *textin, char *chain)
                   1917: {
                   1918:   /* Counts the number of occurence of "chain"  in string textin */
                   1919:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1920:   char *strloc;
                   1921:   
                   1922:   int i,j=0;
                   1923: 
                   1924:   i=0;
                   1925: 
                   1926:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1927:   for(;;) {
                   1928:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1929:     if(strloc != NULL){
                   1930:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1931:       j++;
                   1932:     }else
                   1933:       break;
                   1934:   }
                   1935:   return j;
                   1936:   
                   1937: }
1.137     brouard  1938: /* void cutv(char *u,char *v, char*t, char occ) */
                   1939: /* { */
                   1940: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1941: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1942: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1943: /*   int i,lg,j,p=0; */
                   1944: /*   i=0; */
                   1945: /*   lg=strlen(t); */
                   1946: /*   for(j=0; j<=lg-1; j++) { */
                   1947: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1948: /*   } */
1.126     brouard  1949: 
1.137     brouard  1950: /*   for(j=0; j<p; j++) { */
                   1951: /*     (u[j] = t[j]); */
                   1952: /*   } */
                   1953: /*      u[p]='\0'; */
1.126     brouard  1954: 
1.137     brouard  1955: /*    for(j=0; j<= lg; j++) { */
                   1956: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1957: /*   } */
                   1958: /* } */
1.126     brouard  1959: 
1.160     brouard  1960: #ifdef _WIN32
                   1961: char * strsep(char **pp, const char *delim)
                   1962: {
                   1963:   char *p, *q;
                   1964:          
                   1965:   if ((p = *pp) == NULL)
                   1966:     return 0;
                   1967:   if ((q = strpbrk (p, delim)) != NULL)
                   1968:   {
                   1969:     *pp = q + 1;
                   1970:     *q = '\0';
                   1971:   }
                   1972:   else
                   1973:     *pp = 0;
                   1974:   return p;
                   1975: }
                   1976: #endif
                   1977: 
1.126     brouard  1978: /********************** nrerror ********************/
                   1979: 
                   1980: void nrerror(char error_text[])
                   1981: {
                   1982:   fprintf(stderr,"ERREUR ...\n");
                   1983:   fprintf(stderr,"%s\n",error_text);
                   1984:   exit(EXIT_FAILURE);
                   1985: }
                   1986: /*********************** vector *******************/
                   1987: double *vector(int nl, int nh)
                   1988: {
                   1989:   double *v;
                   1990:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1991:   if (!v) nrerror("allocation failure in vector");
                   1992:   return v-nl+NR_END;
                   1993: }
                   1994: 
                   1995: /************************ free vector ******************/
                   1996: void free_vector(double*v, int nl, int nh)
                   1997: {
                   1998:   free((FREE_ARG)(v+nl-NR_END));
                   1999: }
                   2000: 
                   2001: /************************ivector *******************************/
                   2002: int *ivector(long nl,long nh)
                   2003: {
                   2004:   int *v;
                   2005:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2006:   if (!v) nrerror("allocation failure in ivector");
                   2007:   return v-nl+NR_END;
                   2008: }
                   2009: 
                   2010: /******************free ivector **************************/
                   2011: void free_ivector(int *v, long nl, long nh)
                   2012: {
                   2013:   free((FREE_ARG)(v+nl-NR_END));
                   2014: }
                   2015: 
                   2016: /************************lvector *******************************/
                   2017: long *lvector(long nl,long nh)
                   2018: {
                   2019:   long *v;
                   2020:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2021:   if (!v) nrerror("allocation failure in ivector");
                   2022:   return v-nl+NR_END;
                   2023: }
                   2024: 
                   2025: /******************free lvector **************************/
                   2026: void free_lvector(long *v, long nl, long nh)
                   2027: {
                   2028:   free((FREE_ARG)(v+nl-NR_END));
                   2029: }
                   2030: 
                   2031: /******************* imatrix *******************************/
                   2032: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2033:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2034: { 
                   2035:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2036:   int **m; 
                   2037:   
                   2038:   /* allocate pointers to rows */ 
                   2039:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2040:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2041:   m += NR_END; 
                   2042:   m -= nrl; 
                   2043:   
                   2044:   
                   2045:   /* allocate rows and set pointers to them */ 
                   2046:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2047:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2048:   m[nrl] += NR_END; 
                   2049:   m[nrl] -= ncl; 
                   2050:   
                   2051:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2052:   
                   2053:   /* return pointer to array of pointers to rows */ 
                   2054:   return m; 
                   2055: } 
                   2056: 
                   2057: /****************** free_imatrix *************************/
                   2058: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2059:       int **m;
                   2060:       long nch,ncl,nrh,nrl; 
                   2061:      /* free an int matrix allocated by imatrix() */ 
                   2062: { 
                   2063:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2064:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2065: } 
                   2066: 
                   2067: /******************* matrix *******************************/
                   2068: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2069: {
                   2070:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2071:   double **m;
                   2072: 
                   2073:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2074:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2075:   m += NR_END;
                   2076:   m -= nrl;
                   2077: 
                   2078:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2079:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2080:   m[nrl] += NR_END;
                   2081:   m[nrl] -= ncl;
                   2082: 
                   2083:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2084:   return m;
1.145     brouard  2085:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2086: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2087: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2088:    */
                   2089: }
                   2090: 
                   2091: /*************************free matrix ************************/
                   2092: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2093: {
                   2094:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2095:   free((FREE_ARG)(m+nrl-NR_END));
                   2096: }
                   2097: 
                   2098: /******************* ma3x *******************************/
                   2099: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2100: {
                   2101:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2102:   double ***m;
                   2103: 
                   2104:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2105:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2106:   m += NR_END;
                   2107:   m -= nrl;
                   2108: 
                   2109:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2110:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2111:   m[nrl] += NR_END;
                   2112:   m[nrl] -= ncl;
                   2113: 
                   2114:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2115: 
                   2116:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2117:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2118:   m[nrl][ncl] += NR_END;
                   2119:   m[nrl][ncl] -= nll;
                   2120:   for (j=ncl+1; j<=nch; j++) 
                   2121:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2122:   
                   2123:   for (i=nrl+1; i<=nrh; i++) {
                   2124:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2125:     for (j=ncl+1; j<=nch; j++) 
                   2126:       m[i][j]=m[i][j-1]+nlay;
                   2127:   }
                   2128:   return m; 
                   2129:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2130:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2131:   */
                   2132: }
                   2133: 
                   2134: /*************************free ma3x ************************/
                   2135: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2136: {
                   2137:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2138:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2139:   free((FREE_ARG)(m+nrl-NR_END));
                   2140: }
                   2141: 
                   2142: /*************** function subdirf ***********/
                   2143: char *subdirf(char fileres[])
                   2144: {
                   2145:   /* Caution optionfilefiname is hidden */
                   2146:   strcpy(tmpout,optionfilefiname);
                   2147:   strcat(tmpout,"/"); /* Add to the right */
                   2148:   strcat(tmpout,fileres);
                   2149:   return tmpout;
                   2150: }
                   2151: 
                   2152: /*************** function subdirf2 ***********/
                   2153: char *subdirf2(char fileres[], char *preop)
                   2154: {
1.314     brouard  2155:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2156:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2157:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2158:   /* Caution optionfilefiname is hidden */
                   2159:   strcpy(tmpout,optionfilefiname);
                   2160:   strcat(tmpout,"/");
                   2161:   strcat(tmpout,preop);
                   2162:   strcat(tmpout,fileres);
                   2163:   return tmpout;
                   2164: }
                   2165: 
                   2166: /*************** function subdirf3 ***********/
                   2167: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2168: {
                   2169:   
                   2170:   /* Caution optionfilefiname is hidden */
                   2171:   strcpy(tmpout,optionfilefiname);
                   2172:   strcat(tmpout,"/");
                   2173:   strcat(tmpout,preop);
                   2174:   strcat(tmpout,preop2);
                   2175:   strcat(tmpout,fileres);
                   2176:   return tmpout;
                   2177: }
1.213     brouard  2178:  
                   2179: /*************** function subdirfext ***********/
                   2180: char *subdirfext(char fileres[], char *preop, char *postop)
                   2181: {
                   2182:   
                   2183:   strcpy(tmpout,preop);
                   2184:   strcat(tmpout,fileres);
                   2185:   strcat(tmpout,postop);
                   2186:   return tmpout;
                   2187: }
1.126     brouard  2188: 
1.213     brouard  2189: /*************** function subdirfext3 ***********/
                   2190: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2191: {
                   2192:   
                   2193:   /* Caution optionfilefiname is hidden */
                   2194:   strcpy(tmpout,optionfilefiname);
                   2195:   strcat(tmpout,"/");
                   2196:   strcat(tmpout,preop);
                   2197:   strcat(tmpout,fileres);
                   2198:   strcat(tmpout,postop);
                   2199:   return tmpout;
                   2200: }
                   2201:  
1.162     brouard  2202: char *asc_diff_time(long time_sec, char ascdiff[])
                   2203: {
                   2204:   long sec_left, days, hours, minutes;
                   2205:   days = (time_sec) / (60*60*24);
                   2206:   sec_left = (time_sec) % (60*60*24);
                   2207:   hours = (sec_left) / (60*60) ;
                   2208:   sec_left = (sec_left) %(60*60);
                   2209:   minutes = (sec_left) /60;
                   2210:   sec_left = (sec_left) % (60);
                   2211:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2212:   return ascdiff;
                   2213: }
                   2214: 
1.126     brouard  2215: /***************** f1dim *************************/
                   2216: extern int ncom; 
                   2217: extern double *pcom,*xicom;
                   2218: extern double (*nrfunc)(double []); 
                   2219:  
                   2220: double f1dim(double x) 
                   2221: { 
                   2222:   int j; 
                   2223:   double f;
                   2224:   double *xt; 
                   2225:  
                   2226:   xt=vector(1,ncom); 
                   2227:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2228:   f=(*nrfunc)(xt); 
                   2229:   free_vector(xt,1,ncom); 
                   2230:   return f; 
                   2231: } 
                   2232: 
                   2233: /*****************brent *************************/
                   2234: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2235: {
                   2236:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2237:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2238:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2239:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2240:    * returned function value. 
                   2241:   */
1.126     brouard  2242:   int iter; 
                   2243:   double a,b,d,etemp;
1.159     brouard  2244:   double fu=0,fv,fw,fx;
1.164     brouard  2245:   double ftemp=0.;
1.126     brouard  2246:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2247:   double e=0.0; 
                   2248:  
                   2249:   a=(ax < cx ? ax : cx); 
                   2250:   b=(ax > cx ? ax : cx); 
                   2251:   x=w=v=bx; 
                   2252:   fw=fv=fx=(*f)(x); 
                   2253:   for (iter=1;iter<=ITMAX;iter++) { 
                   2254:     xm=0.5*(a+b); 
                   2255:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2256:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2257:     printf(".");fflush(stdout);
                   2258:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2259: #ifdef DEBUGBRENT
1.126     brouard  2260:     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);
                   2261:     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);
                   2262:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2263: #endif
                   2264:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2265:       *xmin=x; 
                   2266:       return fx; 
                   2267:     } 
                   2268:     ftemp=fu;
                   2269:     if (fabs(e) > tol1) { 
                   2270:       r=(x-w)*(fx-fv); 
                   2271:       q=(x-v)*(fx-fw); 
                   2272:       p=(x-v)*q-(x-w)*r; 
                   2273:       q=2.0*(q-r); 
                   2274:       if (q > 0.0) p = -p; 
                   2275:       q=fabs(q); 
                   2276:       etemp=e; 
                   2277:       e=d; 
                   2278:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2279:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2280:       else { 
1.224     brouard  2281:                                d=p/q; 
                   2282:                                u=x+d; 
                   2283:                                if (u-a < tol2 || b-u < tol2) 
                   2284:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2285:       } 
                   2286:     } else { 
                   2287:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2288:     } 
                   2289:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2290:     fu=(*f)(u); 
                   2291:     if (fu <= fx) { 
                   2292:       if (u >= x) a=x; else b=x; 
                   2293:       SHFT(v,w,x,u) 
1.183     brouard  2294:       SHFT(fv,fw,fx,fu) 
                   2295:     } else { 
                   2296:       if (u < x) a=u; else b=u; 
                   2297:       if (fu <= fw || w == x) { 
1.224     brouard  2298:                                v=w; 
                   2299:                                w=u; 
                   2300:                                fv=fw; 
                   2301:                                fw=fu; 
1.183     brouard  2302:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2303:                                v=u; 
                   2304:                                fv=fu; 
1.183     brouard  2305:       } 
                   2306:     } 
1.126     brouard  2307:   } 
                   2308:   nrerror("Too many iterations in brent"); 
                   2309:   *xmin=x; 
                   2310:   return fx; 
                   2311: } 
                   2312: 
                   2313: /****************** mnbrak ***********************/
                   2314: 
                   2315: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2316:            double (*func)(double)) 
1.183     brouard  2317: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2318: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2319: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2320: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2321:    */
1.126     brouard  2322:   double ulim,u,r,q, dum;
                   2323:   double fu; 
1.187     brouard  2324: 
                   2325:   double scale=10.;
                   2326:   int iterscale=0;
                   2327: 
                   2328:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2329:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2330: 
                   2331: 
                   2332:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2333:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2334:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2335:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2336:   /* } */
                   2337: 
1.126     brouard  2338:   if (*fb > *fa) { 
                   2339:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2340:     SHFT(dum,*fb,*fa,dum) 
                   2341:   } 
1.126     brouard  2342:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2343:   *fc=(*func)(*cx); 
1.183     brouard  2344: #ifdef DEBUG
1.224     brouard  2345:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2346:   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  2347: #endif
1.224     brouard  2348:   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  2349:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2350:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2351:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2352:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2353:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2354:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2355:       fu=(*func)(u); 
1.163     brouard  2356: #ifdef DEBUG
                   2357:       /* f(x)=A(x-u)**2+f(u) */
                   2358:       double A, fparabu; 
                   2359:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2360:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2361:       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);
                   2362:       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  2363:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2364:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2365:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2366:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2367: #endif 
1.184     brouard  2368: #ifdef MNBRAKORIGINAL
1.183     brouard  2369: #else
1.191     brouard  2370: /*       if (fu > *fc) { */
                   2371: /* #ifdef DEBUG */
                   2372: /*       printf("mnbrak4  fu > fc \n"); */
                   2373: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2374: /* #endif */
                   2375: /*     /\* 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 *\\/  *\/ */
                   2376: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2377: /*     dum=u; /\* Shifting c and u *\/ */
                   2378: /*     u = *cx; */
                   2379: /*     *cx = dum; */
                   2380: /*     dum = fu; */
                   2381: /*     fu = *fc; */
                   2382: /*     *fc =dum; */
                   2383: /*       } else { /\* end *\/ */
                   2384: /* #ifdef DEBUG */
                   2385: /*       printf("mnbrak3  fu < fc \n"); */
                   2386: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2387: /* #endif */
                   2388: /*     dum=u; /\* Shifting c and u *\/ */
                   2389: /*     u = *cx; */
                   2390: /*     *cx = dum; */
                   2391: /*     dum = fu; */
                   2392: /*     fu = *fc; */
                   2393: /*     *fc =dum; */
                   2394: /*       } */
1.224     brouard  2395: #ifdef DEBUGMNBRAK
                   2396:                 double A, fparabu; 
                   2397:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2398:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2399:      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);
                   2400:      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  2401: #endif
1.191     brouard  2402:       dum=u; /* Shifting c and u */
                   2403:       u = *cx;
                   2404:       *cx = dum;
                   2405:       dum = fu;
                   2406:       fu = *fc;
                   2407:       *fc =dum;
1.183     brouard  2408: #endif
1.162     brouard  2409:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2410: #ifdef DEBUG
1.224     brouard  2411:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2412:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2413: #endif
1.126     brouard  2414:       fu=(*func)(u); 
                   2415:       if (fu < *fc) { 
1.183     brouard  2416: #ifdef DEBUG
1.224     brouard  2417:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2418:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2419: #endif
                   2420:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2421:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2422: #ifdef DEBUG
                   2423:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2424: #endif
                   2425:       } 
1.162     brouard  2426:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2427: #ifdef DEBUG
1.224     brouard  2428:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2429:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2430: #endif
1.126     brouard  2431:       u=ulim; 
                   2432:       fu=(*func)(u); 
1.183     brouard  2433:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2434: #ifdef DEBUG
1.224     brouard  2435:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2436:       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  2437: #endif
1.126     brouard  2438:       u=(*cx)+GOLD*(*cx-*bx); 
                   2439:       fu=(*func)(u); 
1.224     brouard  2440: #ifdef DEBUG
                   2441:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2442:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2443: #endif
1.183     brouard  2444:     } /* end tests */
1.126     brouard  2445:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2446:     SHFT(*fa,*fb,*fc,fu) 
                   2447: #ifdef DEBUG
1.224     brouard  2448:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2449:       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  2450: #endif
                   2451:   } /* 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  2452: } 
                   2453: 
                   2454: /*************** linmin ************************/
1.162     brouard  2455: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2456: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2457: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2458: the value of func at the returned location p . This is actually all accomplished by calling the
                   2459: routines mnbrak and brent .*/
1.126     brouard  2460: int ncom; 
                   2461: double *pcom,*xicom;
                   2462: double (*nrfunc)(double []); 
                   2463:  
1.224     brouard  2464: #ifdef LINMINORIGINAL
1.126     brouard  2465: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2466: #else
                   2467: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2468: #endif
1.126     brouard  2469: { 
                   2470:   double brent(double ax, double bx, double cx, 
                   2471:               double (*f)(double), double tol, double *xmin); 
                   2472:   double f1dim(double x); 
                   2473:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2474:              double *fc, double (*func)(double)); 
                   2475:   int j; 
                   2476:   double xx,xmin,bx,ax; 
                   2477:   double fx,fb,fa;
1.187     brouard  2478: 
1.203     brouard  2479: #ifdef LINMINORIGINAL
                   2480: #else
                   2481:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2482: #endif
                   2483:   
1.126     brouard  2484:   ncom=n; 
                   2485:   pcom=vector(1,n); 
                   2486:   xicom=vector(1,n); 
                   2487:   nrfunc=func; 
                   2488:   for (j=1;j<=n;j++) { 
                   2489:     pcom[j]=p[j]; 
1.202     brouard  2490:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2491:   } 
1.187     brouard  2492: 
1.203     brouard  2493: #ifdef LINMINORIGINAL
                   2494:   xx=1.;
                   2495: #else
                   2496:   axs=0.0;
                   2497:   xxs=1.;
                   2498:   do{
                   2499:     xx= xxs;
                   2500: #endif
1.187     brouard  2501:     ax=0.;
                   2502:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2503:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2504:     /* 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))   */
                   2505:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2506:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2507:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2508:     /* 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  2509: #ifdef LINMINORIGINAL
                   2510: #else
                   2511:     if (fx != fx){
1.224     brouard  2512:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2513:                        printf("|");
                   2514:                        fprintf(ficlog,"|");
1.203     brouard  2515: #ifdef DEBUGLINMIN
1.224     brouard  2516:                        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  2517: #endif
                   2518:     }
1.224     brouard  2519:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2520: #endif
                   2521:   
1.191     brouard  2522: #ifdef DEBUGLINMIN
                   2523:   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  2524:   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  2525: #endif
1.224     brouard  2526: #ifdef LINMINORIGINAL
                   2527: #else
1.317     brouard  2528:   if(fb == fx){ /* Flat function in the direction */
                   2529:     xmin=xx;
1.224     brouard  2530:     *flat=1;
1.317     brouard  2531:   }else{
1.224     brouard  2532:     *flat=0;
                   2533: #endif
                   2534:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2535:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2536:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2537:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2538:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2539:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2540: #ifdef DEBUG
1.224     brouard  2541:   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);
                   2542:   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);
                   2543: #endif
                   2544: #ifdef LINMINORIGINAL
                   2545: #else
                   2546:                        }
1.126     brouard  2547: #endif
1.191     brouard  2548: #ifdef DEBUGLINMIN
                   2549:   printf("linmin end ");
1.202     brouard  2550:   fprintf(ficlog,"linmin end ");
1.191     brouard  2551: #endif
1.126     brouard  2552:   for (j=1;j<=n;j++) { 
1.203     brouard  2553: #ifdef LINMINORIGINAL
                   2554:     xi[j] *= xmin; 
                   2555: #else
                   2556: #ifdef DEBUGLINMIN
                   2557:     if(xxs <1.0)
                   2558:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2559: #endif
                   2560:     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) */
                   2561: #ifdef DEBUGLINMIN
                   2562:     if(xxs <1.0)
                   2563:       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 );
                   2564: #endif
                   2565: #endif
1.187     brouard  2566:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2567:   } 
1.191     brouard  2568: #ifdef DEBUGLINMIN
1.203     brouard  2569:   printf("\n");
1.191     brouard  2570:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2571:   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  2572:   for (j=1;j<=n;j++) { 
1.202     brouard  2573:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2574:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2575:     if(j % ncovmodel == 0){
1.191     brouard  2576:       printf("\n");
1.202     brouard  2577:       fprintf(ficlog,"\n");
                   2578:     }
1.191     brouard  2579:   }
1.203     brouard  2580: #else
1.191     brouard  2581: #endif
1.126     brouard  2582:   free_vector(xicom,1,n); 
                   2583:   free_vector(pcom,1,n); 
                   2584: } 
                   2585: 
                   2586: 
                   2587: /*************** powell ************************/
1.162     brouard  2588: /*
1.317     brouard  2589: Minimization of a function func of n variables. Input consists in an initial starting point
                   2590: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2591: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2592: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2593: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2594: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2595:  */
1.224     brouard  2596: #ifdef LINMINORIGINAL
                   2597: #else
                   2598:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2599:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2600: #endif
1.126     brouard  2601: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2602:            double (*func)(double [])) 
                   2603: { 
1.224     brouard  2604: #ifdef LINMINORIGINAL
                   2605:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2606:              double (*func)(double [])); 
1.224     brouard  2607: #else 
1.241     brouard  2608:  void linmin(double p[], double xi[], int n, double *fret,
                   2609:             double (*func)(double []),int *flat); 
1.224     brouard  2610: #endif
1.239     brouard  2611:  int i,ibig,j,jk,k; 
1.126     brouard  2612:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2613:   double directest;
1.126     brouard  2614:   double fp,fptt;
                   2615:   double *xits;
                   2616:   int niterf, itmp;
1.349     brouard  2617:   int Bigter=0, nBigterf=1;
                   2618:   
1.126     brouard  2619:   pt=vector(1,n); 
                   2620:   ptt=vector(1,n); 
                   2621:   xit=vector(1,n); 
                   2622:   xits=vector(1,n); 
                   2623:   *fret=(*func)(p); 
                   2624:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2625:   rcurr_time = time(NULL);
                   2626:   fp=(*fret); /* Initialisation */
1.126     brouard  2627:   for (*iter=1;;++(*iter)) { 
                   2628:     ibig=0; 
                   2629:     del=0.0; 
1.157     brouard  2630:     rlast_time=rcurr_time;
1.349     brouard  2631:     rlast_btime=rcurr_time;
1.157     brouard  2632:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2633:     rcurr_time = time(NULL);  
                   2634:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2635:     /* 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); */
                   2636:     /* 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  2637:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2638:     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);
                   2639:     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);
                   2640:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2641:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2642:     for (i=1;i<=n;i++) {
1.126     brouard  2643:       fprintf(ficrespow," %.12lf", p[i]);
                   2644:     }
1.239     brouard  2645:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2646:     printf("\n#model=  1      +     age ");
                   2647:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2648:     if(nagesqr==1){
1.241     brouard  2649:        printf("  + age*age  ");
                   2650:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2651:     }
                   2652:     for(j=1;j <=ncovmodel-2;j++){
                   2653:       if(Typevar[j]==0) {
                   2654:        printf("  +      V%d  ",Tvar[j]);
                   2655:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2656:       }else if(Typevar[j]==1) {
                   2657:        printf("  +    V%d*age ",Tvar[j]);
                   2658:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2659:       }else if(Typevar[j]==2) {
                   2660:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2661:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2662:       }else if(Typevar[j]==3) {
                   2663:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2664:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2665:       }
                   2666:     }
1.126     brouard  2667:     printf("\n");
1.239     brouard  2668: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2669: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2670:     fprintf(ficlog,"\n");
1.239     brouard  2671:     for(i=1,jk=1; i <=nlstate; i++){
                   2672:       for(k=1; k <=(nlstate+ndeath); k++){
                   2673:        if (k != i) {
                   2674:          printf("%d%d ",i,k);
                   2675:          fprintf(ficlog,"%d%d ",i,k);
                   2676:          for(j=1; j <=ncovmodel; j++){
                   2677:            printf("%12.7f ",p[jk]);
                   2678:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2679:            jk++; 
                   2680:          }
                   2681:          printf("\n");
                   2682:          fprintf(ficlog,"\n");
                   2683:        }
                   2684:       }
                   2685:     }
1.241     brouard  2686:     if(*iter <=3 && *iter >1){
1.157     brouard  2687:       tml = *localtime(&rcurr_time);
                   2688:       strcpy(strcurr,asctime(&tml));
                   2689:       rforecast_time=rcurr_time; 
1.126     brouard  2690:       itmp = strlen(strcurr);
                   2691:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2692:        strcurr[itmp-1]='\0';
1.162     brouard  2693:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2694:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2695:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2696:        niterf=nBigterf*ncovmodel;
                   2697:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2698:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2699:        forecast_time = *localtime(&rforecast_time);
                   2700:        strcpy(strfor,asctime(&forecast_time));
                   2701:        itmp = strlen(strfor);
                   2702:        if(strfor[itmp-1]=='\n')
                   2703:          strfor[itmp-1]='\0';
1.349     brouard  2704:        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);
                   2705:        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  2706:       }
                   2707:     }
1.187     brouard  2708:     for (i=1;i<=n;i++) { /* For each direction i */
                   2709:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2710:       fptt=(*fret); 
                   2711: #ifdef DEBUG
1.203     brouard  2712:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2713:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2714: #endif
1.203     brouard  2715:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2716:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2717: #ifdef LINMINORIGINAL
1.188     brouard  2718:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2719: #else
                   2720:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2721:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2722: #endif
                   2723:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2724:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2725:                                /* because that direction will be replaced unless the gain del is small */
                   2726:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2727:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2728:                                /* with the new direction. */
                   2729:                                del=fabs(fptt-(*fret)); 
                   2730:                                ibig=i; 
1.126     brouard  2731:       } 
                   2732: #ifdef DEBUG
                   2733:       printf("%d %.12e",i,(*fret));
                   2734:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2735:       for (j=1;j<=n;j++) {
1.224     brouard  2736:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2737:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2738:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2739:       }
                   2740:       for(j=1;j<=n;j++) {
1.225     brouard  2741:                                printf(" p(%d)=%.12e",j,p[j]);
                   2742:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2743:       }
                   2744:       printf("\n");
                   2745:       fprintf(ficlog,"\n");
                   2746: #endif
1.187     brouard  2747:     } /* end loop on each direction i */
                   2748:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2749:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2750:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2751:     for(j=1;j<=n;j++) {
                   2752:       if(flatdir[j] >0){
                   2753:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2754:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2755:       }
1.319     brouard  2756:       /* printf("\n"); */
                   2757:       /* fprintf(ficlog,"\n"); */
                   2758:     }
1.243     brouard  2759:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2760:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2761:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2762:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2763:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2764:       /* decreased of more than 3.84  */
                   2765:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2766:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2767:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2768:                        
1.188     brouard  2769:       /* Starting the program with initial values given by a former maximization will simply change */
                   2770:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2771:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2772:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2773: #ifdef DEBUG
                   2774:       int k[2],l;
                   2775:       k[0]=1;
                   2776:       k[1]=-1;
                   2777:       printf("Max: %.12e",(*func)(p));
                   2778:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2779:       for (j=1;j<=n;j++) {
                   2780:        printf(" %.12e",p[j]);
                   2781:        fprintf(ficlog," %.12e",p[j]);
                   2782:       }
                   2783:       printf("\n");
                   2784:       fprintf(ficlog,"\n");
                   2785:       for(l=0;l<=1;l++) {
                   2786:        for (j=1;j<=n;j++) {
                   2787:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2788:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2789:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2790:        }
                   2791:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2792:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2793:       }
                   2794: #endif
                   2795: 
                   2796:       free_vector(xit,1,n); 
                   2797:       free_vector(xits,1,n); 
                   2798:       free_vector(ptt,1,n); 
                   2799:       free_vector(pt,1,n); 
                   2800:       return; 
1.192     brouard  2801:     } /* enough precision */ 
1.240     brouard  2802:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2803:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2804:       ptt[j]=2.0*p[j]-pt[j]; 
                   2805:       xit[j]=p[j]-pt[j]; 
                   2806:       pt[j]=p[j]; 
                   2807:     } 
1.181     brouard  2808:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2809: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2810:                if (*iter <=4) {
1.225     brouard  2811: #else
                   2812: #endif
1.224     brouard  2813: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2814: #else
1.161     brouard  2815:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2816: #endif
1.162     brouard  2817:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2818:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2819:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2820:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2821:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2822:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2823:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2824:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2825:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2826:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2827:       /* mu² and del² are equal when f3=f1 */
                   2828:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2829:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2830:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2831:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2832: #ifdef NRCORIGINAL
                   2833:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2834: #else
                   2835:       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  2836:       t= t- del*SQR(fp-fptt);
1.183     brouard  2837: #endif
1.202     brouard  2838:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2839: #ifdef DEBUG
1.181     brouard  2840:       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);
                   2841:       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  2842:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2843:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2844:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2845:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2846:       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);
                   2847:       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);
                   2848: #endif
1.183     brouard  2849: #ifdef POWELLORIGINAL
                   2850:       if (t < 0.0) { /* Then we use it for new direction */
                   2851: #else
1.182     brouard  2852:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2853:                                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  2854:         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  2855:         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  2856:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2857:       } 
1.181     brouard  2858:       if (directest < 0.0) { /* Then we use it for new direction */
                   2859: #endif
1.191     brouard  2860: #ifdef DEBUGLINMIN
1.234     brouard  2861:        printf("Before linmin in direction P%d-P0\n",n);
                   2862:        for (j=1;j<=n;j++) {
                   2863:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2864:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2865:          if(j % ncovmodel == 0){
                   2866:            printf("\n");
                   2867:            fprintf(ficlog,"\n");
                   2868:          }
                   2869:        }
1.224     brouard  2870: #endif
                   2871: #ifdef LINMINORIGINAL
1.234     brouard  2872:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2873: #else
1.234     brouard  2874:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2875:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2876: #endif
1.234     brouard  2877:        
1.191     brouard  2878: #ifdef DEBUGLINMIN
1.234     brouard  2879:        for (j=1;j<=n;j++) { 
                   2880:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2881:          fprintf(ficlog,"After 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
1.234     brouard  2888:        for (j=1;j<=n;j++) { 
                   2889:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2890:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2891:        }
1.224     brouard  2892: #ifdef LINMINORIGINAL
                   2893: #else
1.234     brouard  2894:        for (j=1, flatd=0;j<=n;j++) {
                   2895:          if(flatdir[j]>0)
                   2896:            flatd++;
                   2897:        }
                   2898:        if(flatd >0){
1.255     brouard  2899:          printf("%d flat directions: ",flatd);
                   2900:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2901:          for (j=1;j<=n;j++) { 
                   2902:            if(flatdir[j]>0){
                   2903:              printf("%d ",j);
                   2904:              fprintf(ficlog,"%d ",j);
                   2905:            }
                   2906:          }
                   2907:          printf("\n");
                   2908:          fprintf(ficlog,"\n");
1.319     brouard  2909: #ifdef FLATSUP
                   2910:           free_vector(xit,1,n); 
                   2911:           free_vector(xits,1,n); 
                   2912:           free_vector(ptt,1,n); 
                   2913:           free_vector(pt,1,n); 
                   2914:           return;
                   2915: #endif
1.234     brouard  2916:        }
1.191     brouard  2917: #endif
1.234     brouard  2918:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2919:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2920:        
1.126     brouard  2921: #ifdef DEBUG
1.234     brouard  2922:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2923:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2924:        for(j=1;j<=n;j++){
                   2925:          printf(" %lf",xit[j]);
                   2926:          fprintf(ficlog," %lf",xit[j]);
                   2927:        }
                   2928:        printf("\n");
                   2929:        fprintf(ficlog,"\n");
1.126     brouard  2930: #endif
1.192     brouard  2931:       } /* end of t or directest negative */
1.224     brouard  2932: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2933: #else
1.234     brouard  2934:       } /* end if (fptt < fp)  */
1.192     brouard  2935: #endif
1.225     brouard  2936: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2937:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2938: #else
1.224     brouard  2939: #endif
1.234     brouard  2940:                } /* loop iteration */ 
1.126     brouard  2941: } 
1.234     brouard  2942:   
1.126     brouard  2943: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2944:   
1.235     brouard  2945:   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  2946:   {
1.338     brouard  2947:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2948:      *   (and selected quantitative values in nres)
                   2949:      *  by left multiplying the unit
                   2950:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2951:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2952:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2953:      * or prevalence in state 1, prevalence in state 2, 0
                   2954:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2955:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2956:      * Output is prlim.
                   2957:      * Initial matrix pimij 
                   2958:      */
1.206     brouard  2959:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2960:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2961:   /*  0,                   0                  , 1} */
                   2962:   /*
                   2963:    * and after some iteration: */
                   2964:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2965:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2966:   /*  0,                   0                  , 1} */
                   2967:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2968:   /* {0.51571254859325999, 0.4842874514067399, */
                   2969:   /*  0.51326036147820708, 0.48673963852179264} */
                   2970:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2971:     
1.332     brouard  2972:     int i, ii,j,k, k1;
1.209     brouard  2973:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2974:   /* double **matprod2(); */ /* test */
1.218     brouard  2975:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2976:   double **newm;
1.209     brouard  2977:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2978:   int ncvloop=0;
1.288     brouard  2979:   int first=0;
1.169     brouard  2980:   
1.209     brouard  2981:   min=vector(1,nlstate);
                   2982:   max=vector(1,nlstate);
                   2983:   meandiff=vector(1,nlstate);
                   2984: 
1.218     brouard  2985:        /* Starting with matrix unity */
1.126     brouard  2986:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2987:     for (j=1;j<=nlstate+ndeath;j++){
                   2988:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2989:     }
1.169     brouard  2990:   
                   2991:   cov[1]=1.;
                   2992:   
                   2993:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2994:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2995:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2996:     ncvloop++;
1.126     brouard  2997:     newm=savm;
                   2998:     /* Covariates have to be included here again */
1.138     brouard  2999:     cov[2]=agefin;
1.319     brouard  3000:      if(nagesqr==1){
                   3001:       cov[3]= agefin*agefin;
                   3002:      }
1.332     brouard  3003:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3004:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3005:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3006:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3007:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3008:        }else{
                   3009:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3010:        }
                   3011:      }/* End of loop on model equation */
                   3012:      
                   3013: /* Start of old code (replaced by a loop on position in the model equation */
                   3014:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3015:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3016:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3017:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3018:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3019:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3020:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3021:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3022:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3023:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3024:     /*    *nsd=3                              (1)  (2)           (3) */
                   3025:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3026:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3027:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3028:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3029:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3030:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3031:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3032:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3033:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3034:     /*    *TvarsDpType */
                   3035:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3036:     /*    * nsd=1              (1)           (2) */
                   3037:     /*    *TvarsD[nsd]          3             2 */
                   3038:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3039:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3040:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3041:     /*    *\/ */
                   3042:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3043:     /*   /\* 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)); *\/ */
                   3044:     /* } */
                   3045:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3046:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3047:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3048:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3049:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3050:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3051:     /*   /\* 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]); *\/ */
                   3052:     /* } */
                   3053:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3054:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3055:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3056:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3057:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3058:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3059:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3060:     /*   } */
                   3061:     /*   /\* 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]); *\/ */
                   3062:     /* } */
                   3063:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3064:     /*   /\* 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]); *\/ */
                   3065:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3066:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3067:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3068:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3069:     /*         }else{ */
                   3070:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3071:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3072:     /*         } */
                   3073:     /*   }else{ */
                   3074:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3075:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3076:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3077:     /*         }else{ */
                   3078:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3079:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3080:     /*         } */
                   3081:     /*   } */
                   3082:     /* } /\* End product without age *\/ */
                   3083: /* ENd of old code */
1.138     brouard  3084:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3085:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3086:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3087:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3088:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3089:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3090:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3091:     
1.126     brouard  3092:     savm=oldm;
                   3093:     oldm=newm;
1.209     brouard  3094: 
                   3095:     for(j=1; j<=nlstate; j++){
                   3096:       max[j]=0.;
                   3097:       min[j]=1.;
                   3098:     }
                   3099:     for(i=1;i<=nlstate;i++){
                   3100:       sumnew=0;
                   3101:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3102:       for(j=1; j<=nlstate; j++){ 
                   3103:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3104:        max[j]=FMAX(max[j],prlim[i][j]);
                   3105:        min[j]=FMIN(min[j],prlim[i][j]);
                   3106:       }
                   3107:     }
                   3108: 
1.126     brouard  3109:     maxmax=0.;
1.209     brouard  3110:     for(j=1; j<=nlstate; j++){
                   3111:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3112:       maxmax=FMAX(maxmax,meandiff[j]);
                   3113:       /* 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  3114:     } /* j loop */
1.203     brouard  3115:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3116:     /* 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  3117:     if(maxmax < ftolpl){
1.209     brouard  3118:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3119:       free_vector(min,1,nlstate);
                   3120:       free_vector(max,1,nlstate);
                   3121:       free_vector(meandiff,1,nlstate);
1.126     brouard  3122:       return prlim;
                   3123:     }
1.288     brouard  3124:   } /* agefin loop */
1.208     brouard  3125:     /* After some age loop it doesn't converge */
1.288     brouard  3126:   if(!first){
                   3127:     first=1;
                   3128:     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  3129:     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);
                   3130:   }else if (first >=1 && first <10){
                   3131:     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);
                   3132:     first++;
                   3133:   }else if (first ==10){
                   3134:     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);
                   3135:     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");
                   3136:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3137:     first++;
1.288     brouard  3138:   }
                   3139: 
1.209     brouard  3140:   /* 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); */
                   3141:   free_vector(min,1,nlstate);
                   3142:   free_vector(max,1,nlstate);
                   3143:   free_vector(meandiff,1,nlstate);
1.208     brouard  3144:   
1.169     brouard  3145:   return prlim; /* should not reach here */
1.126     brouard  3146: }
                   3147: 
1.217     brouard  3148: 
                   3149:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3150: 
1.218     brouard  3151:  /* 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) */
                   3152:  /* 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  3153:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3154: {
1.264     brouard  3155:   /* 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  3156:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3157:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3158:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3159:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3160:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3161:   /* Initial matrix pimij */
                   3162:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3163:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3164:   /*  0,                   0                  , 1} */
                   3165:   /*
                   3166:    * and after some iteration: */
                   3167:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3168:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3169:   /*  0,                   0                  , 1} */
                   3170:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3171:   /* {0.51571254859325999, 0.4842874514067399, */
                   3172:   /*  0.51326036147820708, 0.48673963852179264} */
                   3173:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3174: 
1.332     brouard  3175:   int i, ii,j,k, k1;
1.247     brouard  3176:   int first=0;
1.217     brouard  3177:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3178:   /* double **matprod2(); */ /* test */
                   3179:   double **out, cov[NCOVMAX+1], **bmij();
                   3180:   double **newm;
1.218     brouard  3181:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3182:   double        **oldm, **savm;  /* for use */
                   3183: 
1.217     brouard  3184:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3185:   int ncvloop=0;
                   3186:   
                   3187:   min=vector(1,nlstate);
                   3188:   max=vector(1,nlstate);
                   3189:   meandiff=vector(1,nlstate);
                   3190: 
1.266     brouard  3191:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3192:   oldm=oldms; savm=savms;
                   3193:   
                   3194:   /* Starting with matrix unity */
                   3195:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3196:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3197:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3198:     }
                   3199:   
                   3200:   cov[1]=1.;
                   3201:   
                   3202:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3203:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3204:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3205:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3206:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3207:     ncvloop++;
1.218     brouard  3208:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3209:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3210:     /* Covariates have to be included here again */
                   3211:     cov[2]=agefin;
1.319     brouard  3212:     if(nagesqr==1){
1.217     brouard  3213:       cov[3]= agefin*agefin;;
1.319     brouard  3214:     }
1.332     brouard  3215:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3216:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3217:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3218:       }else{
1.332     brouard  3219:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3220:       }
1.332     brouard  3221:     }/* End of loop on model equation */
                   3222: 
                   3223: /* Old code */ 
                   3224: 
                   3225:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3226:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3227:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3228:     /*   /\* 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)); *\/ */
                   3229:     /* } */
                   3230:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3231:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3232:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3233:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3234:     /* /\* } *\/ */
                   3235:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3236:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3237:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3238:     /*   /\* 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]); *\/ */
                   3239:     /* } */
                   3240:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3241:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3242:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3243:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3244:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3245:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3246:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3247:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3248:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3249:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3250:     /*   } */
                   3251:     /*   /\* 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]); *\/ */
                   3252:     /* } */
                   3253:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3254:     /*   /\* 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]); *\/ */
                   3255:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3256:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3257:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3258:     /*         }else{ */
                   3259:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3260:     /*         } */
                   3261:     /*   }else{ */
                   3262:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3263:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3264:     /*         }else{ */
                   3265:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3266:     /*         } */
                   3267:     /*   } */
                   3268:     /* } */
1.217     brouard  3269:     
                   3270:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3271:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3272:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3273:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3274:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3275:                /* ij should be linked to the correct index of cov */
                   3276:                /* age and covariate values ij are in 'cov', but we need to pass
                   3277:                 * ij for the observed prevalence at age and status and covariate
                   3278:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3279:                 */
                   3280:     /* 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 *\/ */
                   3281:     /* 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 *\/ */
                   3282:     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  3283:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3284:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3285:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3286:     /*         printf("%d newm= ",i); */
                   3287:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3288:     /*           printf("%f ",newm[i][j]); */
                   3289:     /*         } */
                   3290:     /*         printf("oldm * "); */
                   3291:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3292:     /*           printf("%f ",oldm[i][j]); */
                   3293:     /*         } */
1.268     brouard  3294:     /*         printf(" bmmij "); */
1.266     brouard  3295:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3296:     /*           printf("%f ",pmmij[i][j]); */
                   3297:     /*         } */
                   3298:     /*         printf("\n"); */
                   3299:     /*   } */
                   3300:     /* } */
1.217     brouard  3301:     savm=oldm;
                   3302:     oldm=newm;
1.266     brouard  3303: 
1.217     brouard  3304:     for(j=1; j<=nlstate; j++){
                   3305:       max[j]=0.;
                   3306:       min[j]=1.;
                   3307:     }
                   3308:     for(j=1; j<=nlstate; j++){ 
                   3309:       for(i=1;i<=nlstate;i++){
1.234     brouard  3310:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3311:        bprlim[i][j]= newm[i][j];
                   3312:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3313:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3314:       }
                   3315:     }
1.218     brouard  3316:                
1.217     brouard  3317:     maxmax=0.;
                   3318:     for(i=1; i<=nlstate; i++){
1.318     brouard  3319:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3320:       maxmax=FMAX(maxmax,meandiff[i]);
                   3321:       /* 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  3322:     } /* i loop */
1.217     brouard  3323:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3324:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3325:     if(maxmax < ftolpl){
1.220     brouard  3326:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3327:       free_vector(min,1,nlstate);
                   3328:       free_vector(max,1,nlstate);
                   3329:       free_vector(meandiff,1,nlstate);
                   3330:       return bprlim;
                   3331:     }
1.288     brouard  3332:   } /* agefin loop */
1.217     brouard  3333:     /* After some age loop it doesn't converge */
1.288     brouard  3334:   if(!first){
1.247     brouard  3335:     first=1;
                   3336:     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\
                   3337: 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);
                   3338:   }
                   3339:   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  3340: 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);
                   3341:   /* 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); */
                   3342:   free_vector(min,1,nlstate);
                   3343:   free_vector(max,1,nlstate);
                   3344:   free_vector(meandiff,1,nlstate);
                   3345:   
                   3346:   return bprlim; /* should not reach here */
                   3347: }
                   3348: 
1.126     brouard  3349: /*************** transition probabilities ***************/ 
                   3350: 
                   3351: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3352: {
1.138     brouard  3353:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3354:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3355:      model to the ncovmodel covariates (including constant and age).
                   3356:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3357:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3358:      ncth covariate in the global vector x is given by the formula:
                   3359:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3360:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3361:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3362:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3363:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3364:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3365:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3366:   */
                   3367:   double s1, lnpijopii;
1.126     brouard  3368:   /*double t34;*/
1.164     brouard  3369:   int i,j, nc, ii, jj;
1.126     brouard  3370: 
1.223     brouard  3371:   for(i=1; i<= nlstate; i++){
                   3372:     for(j=1; j<i;j++){
                   3373:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3374:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3375:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3376:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3377:       }
                   3378:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3379:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3380:     }
                   3381:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3382:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3383:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3384:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3385:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3386:       }
                   3387:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3388:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3389:     }
                   3390:   }
1.218     brouard  3391:   
1.223     brouard  3392:   for(i=1; i<= nlstate; i++){
                   3393:     s1=0;
                   3394:     for(j=1; j<i; j++){
1.339     brouard  3395:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3396:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3397:     }
                   3398:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3399:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3400:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3401:     }
                   3402:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3403:     ps[i][i]=1./(s1+1.);
                   3404:     /* Computing other pijs */
                   3405:     for(j=1; j<i; j++)
1.325     brouard  3406:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3407:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3408:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3409:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3410:   } /* end i */
1.218     brouard  3411:   
1.223     brouard  3412:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3413:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3414:       ps[ii][jj]=0;
                   3415:       ps[ii][ii]=1;
                   3416:     }
                   3417:   }
1.294     brouard  3418: 
                   3419: 
1.223     brouard  3420:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3421:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3422:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3423:   /*   } */
                   3424:   /*   printf("\n "); */
                   3425:   /* } */
                   3426:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3427:   /*
                   3428:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3429:                goto end;*/
1.266     brouard  3430:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3431: }
                   3432: 
1.218     brouard  3433: /*************** backward transition probabilities ***************/ 
                   3434: 
                   3435:  /* 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 ) */
                   3436: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3437:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3438: {
1.302     brouard  3439:   /* 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  3440:    * 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  3441:    */
1.218     brouard  3442:   int i, ii, j,k;
1.222     brouard  3443:   
                   3444:   double **out, **pmij();
                   3445:   double sumnew=0.;
1.218     brouard  3446:   double agefin;
1.292     brouard  3447:   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  3448:   double **dnewm, **dsavm, **doldm;
                   3449:   double **bbmij;
                   3450:   
1.218     brouard  3451:   doldm=ddoldms; /* global pointers */
1.222     brouard  3452:   dnewm=ddnewms;
                   3453:   dsavm=ddsavms;
1.318     brouard  3454: 
                   3455:   /* Debug */
                   3456:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3457:   agefin=cov[2];
1.268     brouard  3458:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3459:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3460:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3461:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3462: 
                   3463:   /* P_x */
1.325     brouard  3464:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3465:   /* outputs pmmij which is a stochastic matrix in row */
                   3466: 
                   3467:   /* Diag(w_x) */
1.292     brouard  3468:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3469:   sumnew=0.;
1.269     brouard  3470:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3471:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3472:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3473:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3474:   }
                   3475:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3476:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3477:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3478:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3479:     }
                   3480:   }else{
                   3481:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3482:       for (j=1;j<=nlstate+ndeath;j++)
                   3483:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3484:     }
                   3485:     /* if(sumnew <0.9){ */
                   3486:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3487:     /* } */
                   3488:   }
                   3489:   k3=0.0;  /* We put the last diagonal to 0 */
                   3490:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3491:       doldm[ii][ii]= k3;
                   3492:   }
                   3493:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3494:   
1.292     brouard  3495:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3496:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3497: 
1.292     brouard  3498:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3499:   /* 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  3500:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3501:     sumnew=0.;
1.222     brouard  3502:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3503:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3504:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3505:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3506:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3507:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3508:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3509:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3510:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3511:        /* }else */
1.268     brouard  3512:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3513:     } /*End ii */
                   3514:   } /* 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 */
                   3515: 
1.292     brouard  3516:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3517:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3518:   /* end bmij */
1.266     brouard  3519:   return ps; /*pointer is unchanged */
1.218     brouard  3520: }
1.217     brouard  3521: /*************** transition probabilities ***************/ 
                   3522: 
1.218     brouard  3523: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3524: {
                   3525:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3526:      computes the probability to be observed in state j being in state i by appying the
                   3527:      model to the ncovmodel covariates (including constant and age).
                   3528:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3529:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3530:      ncth covariate in the global vector x is given by the formula:
                   3531:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3532:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3533:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3534:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3535:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3536:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3537:   */
                   3538:   double s1, lnpijopii;
                   3539:   /*double t34;*/
                   3540:   int i,j, nc, ii, jj;
                   3541: 
1.234     brouard  3542:   for(i=1; i<= nlstate; i++){
                   3543:     for(j=1; j<i;j++){
                   3544:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3545:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3546:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3547:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3548:       }
                   3549:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3550:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3551:     }
                   3552:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3553:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3554:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3555:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3556:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3557:       }
                   3558:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3559:     }
                   3560:   }
                   3561:   
                   3562:   for(i=1; i<= nlstate; i++){
                   3563:     s1=0;
                   3564:     for(j=1; j<i; j++){
                   3565:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3566:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3567:     }
                   3568:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3569:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3570:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3571:     }
                   3572:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3573:     ps[i][i]=1./(s1+1.);
                   3574:     /* Computing other pijs */
                   3575:     for(j=1; j<i; j++)
                   3576:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3577:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3578:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3579:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3580:   } /* end i */
                   3581:   
                   3582:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3583:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3584:       ps[ii][jj]=0;
                   3585:       ps[ii][ii]=1;
                   3586:     }
                   3587:   }
1.296     brouard  3588:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3589:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3590:     s1=0.;
                   3591:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3592:       s1+=ps[ii][jj];
                   3593:     }
                   3594:     for(ii=1; ii<= nlstate; ii++){
                   3595:       ps[ii][jj]=ps[ii][jj]/s1;
                   3596:     }
                   3597:   }
                   3598:   /* Transposition */
                   3599:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3600:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3601:       s1=ps[ii][jj];
                   3602:       ps[ii][jj]=ps[jj][ii];
                   3603:       ps[jj][ii]=s1;
                   3604:     }
                   3605:   }
                   3606:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3607:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3608:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3609:   /*   } */
                   3610:   /*   printf("\n "); */
                   3611:   /* } */
                   3612:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3613:   /*
                   3614:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3615:     goto end;*/
                   3616:   return ps;
1.217     brouard  3617: }
                   3618: 
                   3619: 
1.126     brouard  3620: /**************** Product of 2 matrices ******************/
                   3621: 
1.145     brouard  3622: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3623: {
                   3624:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3625:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3626:   /* in, b, out are matrice of pointers which should have been initialized 
                   3627:      before: only the contents of out is modified. The function returns
                   3628:      a pointer to pointers identical to out */
1.145     brouard  3629:   int i, j, k;
1.126     brouard  3630:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3631:     for(k=ncolol; k<=ncoloh; k++){
                   3632:       out[i][k]=0.;
                   3633:       for(j=ncl; j<=nch; j++)
                   3634:        out[i][k] +=in[i][j]*b[j][k];
                   3635:     }
1.126     brouard  3636:   return out;
                   3637: }
                   3638: 
                   3639: 
                   3640: /************* Higher Matrix Product ***************/
                   3641: 
1.235     brouard  3642: 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  3643: {
1.336     brouard  3644:   /* Already optimized with precov.
                   3645:      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  3646:      'nhstepm*hstepm*stepm' months (i.e. until
                   3647:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3648:      nhstepm*hstepm matrices. 
                   3649:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3650:      (typically every 2 years instead of every month which is too big 
                   3651:      for the memory).
                   3652:      Model is determined by parameters x and covariates have to be 
                   3653:      included manually here. 
                   3654: 
                   3655:      */
                   3656: 
1.330     brouard  3657:   int i, j, d, h, k, k1;
1.131     brouard  3658:   double **out, cov[NCOVMAX+1];
1.126     brouard  3659:   double **newm;
1.187     brouard  3660:   double agexact;
1.214     brouard  3661:   double agebegin, ageend;
1.126     brouard  3662: 
                   3663:   /* Hstepm could be zero and should return the unit matrix */
                   3664:   for (i=1;i<=nlstate+ndeath;i++)
                   3665:     for (j=1;j<=nlstate+ndeath;j++){
                   3666:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3667:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3668:     }
                   3669:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3670:   for(h=1; h <=nhstepm; h++){
                   3671:     for(d=1; d <=hstepm; d++){
                   3672:       newm=savm;
                   3673:       /* Covariates have to be included here again */
                   3674:       cov[1]=1.;
1.214     brouard  3675:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3676:       cov[2]=agexact;
1.319     brouard  3677:       if(nagesqr==1){
1.227     brouard  3678:        cov[3]= agexact*agexact;
1.319     brouard  3679:       }
1.330     brouard  3680:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3681:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3682:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3683:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3684:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3685:        }else{
                   3686:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3687:        }
                   3688:       }/* End of loop on model equation */
                   3689:        /* Old code */ 
                   3690: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3691: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3692: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3693: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3694: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3695: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3696: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3697: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3698: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3699: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3700: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3701: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3702: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3703: /*       /\* 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]])); *\/ */
                   3704: /*       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); */
                   3705: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3706: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3707: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3708: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3709: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3710: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3711: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3712: /*       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]]); */
                   3713: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3714: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3715: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3716: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3717: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3718: /*       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]); */
                   3719: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3720: 
                   3721: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3722: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3723: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3724: /*       /\* *\/ */
1.330     brouard  3725: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3726: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3727: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3728: /* /\*cptcovage=2                   1               2      *\/ */
                   3729: /* /\*Tage[k]=                      5               8      *\/  */
                   3730: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3731: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3732: /*       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]]); */
                   3733: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3734: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3735: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3736: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3737: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3738: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3739: /*       /\*   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); *\/ */
                   3740: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3741: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3742: /*       /\* } *\/ */
                   3743: /*       /\* 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]); *\/ */
                   3744: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3745: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3746: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3747: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3748: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3749: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3750: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3751: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3752: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3753:          
1.332     brouard  3754: /*       /\* 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])]); *\/ */
                   3755: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3756: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3757: /*       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]]); */
                   3758: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3759: 
                   3760: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3761: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3762: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3763: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3764: /*           /\* 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]])]; *\/ */
                   3765: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3766: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3767: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3768: /*       /\*   } *\/ */
                   3769: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3770: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3771: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3772: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3773: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3774: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3775: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3776: /*       /\*   } *\/ */
                   3777: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3778: /*     }/\*end of products *\/ */
                   3779:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3780:       /* for (k=1; k<=cptcovn;k++)  */
                   3781:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3782:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3783:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3784:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3785:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3786:       
                   3787:       
1.126     brouard  3788:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3789:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3790:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3791:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3792:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3793:       /* if((int)age == 70){ */
                   3794:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3795:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3796:       /*         printf("%d pmmij ",i); */
                   3797:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3798:       /*           printf("%f ",pmmij[i][j]); */
                   3799:       /*         } */
                   3800:       /*         printf(" oldm "); */
                   3801:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3802:       /*           printf("%f ",oldm[i][j]); */
                   3803:       /*         } */
                   3804:       /*         printf("\n"); */
                   3805:       /*       } */
                   3806:       /* } */
1.126     brouard  3807:       savm=oldm;
                   3808:       oldm=newm;
                   3809:     }
                   3810:     for(i=1; i<=nlstate+ndeath; i++)
                   3811:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3812:        po[i][j][h]=newm[i][j];
                   3813:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3814:       }
1.128     brouard  3815:     /*printf("h=%d ",h);*/
1.126     brouard  3816:   } /* end h */
1.267     brouard  3817:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3818:   return po;
                   3819: }
                   3820: 
1.217     brouard  3821: /************* Higher Back Matrix Product ***************/
1.218     brouard  3822: /* 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  3823: 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  3824: {
1.332     brouard  3825:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3826:      computes the transition matrix starting at age 'age' over
1.217     brouard  3827:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3828:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3829:      nhstepm*hstepm matrices.
                   3830:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3831:      (typically every 2 years instead of every month which is too big
1.217     brouard  3832:      for the memory).
1.218     brouard  3833:      Model is determined by parameters x and covariates have to be
1.266     brouard  3834:      included manually here. Then we use a call to bmij(x and cov)
                   3835:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3836:   */
1.217     brouard  3837: 
1.332     brouard  3838:   int i, j, d, h, k, k1;
1.266     brouard  3839:   double **out, cov[NCOVMAX+1], **bmij();
                   3840:   double **newm, ***newmm;
1.217     brouard  3841:   double agexact;
                   3842:   double agebegin, ageend;
1.222     brouard  3843:   double **oldm, **savm;
1.217     brouard  3844: 
1.266     brouard  3845:   newmm=po; /* To be saved */
                   3846:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3847:   /* Hstepm could be zero and should return the unit matrix */
                   3848:   for (i=1;i<=nlstate+ndeath;i++)
                   3849:     for (j=1;j<=nlstate+ndeath;j++){
                   3850:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3851:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3852:     }
                   3853:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3854:   for(h=1; h <=nhstepm; h++){
                   3855:     for(d=1; d <=hstepm; d++){
                   3856:       newm=savm;
                   3857:       /* Covariates have to be included here again */
                   3858:       cov[1]=1.;
1.271     brouard  3859:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3860:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3861:         /* Debug */
                   3862:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3863:       cov[2]=agexact;
1.332     brouard  3864:       if(nagesqr==1){
1.222     brouard  3865:        cov[3]= agexact*agexact;
1.332     brouard  3866:       }
                   3867:       /** New code */
                   3868:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3869:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3870:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3871:        }else{
1.332     brouard  3872:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3873:        }
1.332     brouard  3874:       }/* End of loop on model equation */
                   3875:       /** End of new code */
                   3876:   /** This was old code */
                   3877:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3878:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3879:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3880:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3881:       /*   /\* 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)); *\/ */
                   3882:       /* } */
                   3883:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3884:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3885:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3886:       /*       /\* 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]); *\/ */
                   3887:       /* } */
                   3888:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3889:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3890:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3891:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3892:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3893:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3894:       /*       } */
                   3895:       /*       /\* 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]); *\/ */
                   3896:       /* } */
                   3897:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3898:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3899:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3900:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3901:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3902:       /*         }else{ */
                   3903:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3904:       /*         } */
                   3905:       /*       }else{ */
                   3906:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3907:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3908:       /*         }else{ */
                   3909:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3910:       /*         } */
                   3911:       /*       } */
                   3912:       /* }                      */
                   3913:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3914:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3915: /** End of old code */
                   3916:       
1.218     brouard  3917:       /* Careful transposed matrix */
1.266     brouard  3918:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3919:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3920:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3921:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3922:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3923:       /* if((int)age == 70){ */
                   3924:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3925:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3926:       /*         printf("%d pmmij ",i); */
                   3927:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3928:       /*           printf("%f ",pmmij[i][j]); */
                   3929:       /*         } */
                   3930:       /*         printf(" oldm "); */
                   3931:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3932:       /*           printf("%f ",oldm[i][j]); */
                   3933:       /*         } */
                   3934:       /*         printf("\n"); */
                   3935:       /*       } */
                   3936:       /* } */
                   3937:       savm=oldm;
                   3938:       oldm=newm;
                   3939:     }
                   3940:     for(i=1; i<=nlstate+ndeath; i++)
                   3941:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3942:        po[i][j][h]=newm[i][j];
1.268     brouard  3943:        /* if(h==nhstepm) */
                   3944:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3945:       }
1.268     brouard  3946:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3947:   } /* end h */
1.268     brouard  3948:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3949:   return po;
                   3950: }
                   3951: 
                   3952: 
1.162     brouard  3953: #ifdef NLOPT
                   3954:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3955:   double fret;
                   3956:   double *xt;
                   3957:   int j;
                   3958:   myfunc_data *d2 = (myfunc_data *) pd;
                   3959: /* xt = (p1-1); */
                   3960:   xt=vector(1,n); 
                   3961:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3962: 
                   3963:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3964:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3965:   printf("Function = %.12lf ",fret);
                   3966:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3967:   printf("\n");
                   3968:  free_vector(xt,1,n);
                   3969:   return fret;
                   3970: }
                   3971: #endif
1.126     brouard  3972: 
                   3973: /*************** log-likelihood *************/
                   3974: double func( double *x)
                   3975: {
1.336     brouard  3976:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3977:   int ioffset=0;
1.339     brouard  3978:   int ipos=0,iposold=0,ncovv=0;
                   3979: 
1.340     brouard  3980:   double cotvarv, cotvarvold;
1.226     brouard  3981:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3982:   double **out;
                   3983:   double lli; /* Individual log likelihood */
                   3984:   int s1, s2;
1.228     brouard  3985:   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  3986: 
1.226     brouard  3987:   double bbh, survp;
                   3988:   double agexact;
1.336     brouard  3989:   double agebegin, ageend;
1.226     brouard  3990:   /*extern weight */
                   3991:   /* We are differentiating ll according to initial status */
                   3992:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3993:   /*for(i=1;i<imx;i++) 
                   3994:     printf(" %d\n",s[4][i]);
                   3995:   */
1.162     brouard  3996: 
1.226     brouard  3997:   ++countcallfunc;
1.162     brouard  3998: 
1.226     brouard  3999:   cov[1]=1.;
1.126     brouard  4000: 
1.226     brouard  4001:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4002:   ioffset=0;
1.226     brouard  4003:   if(mle==1){
                   4004:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4005:       /* Computes the values of the ncovmodel covariates of the model
                   4006:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4007:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4008:         to be observed in j being in i according to the model.
                   4009:       */
1.243     brouard  4010:       ioffset=2+nagesqr ;
1.233     brouard  4011:    /* Fixed */
1.345     brouard  4012:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4013:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4014:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4015:        /*  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  4016:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4017:        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  4018:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4019:       }
1.226     brouard  4020:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4021:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4022:         has been calculated etc */
                   4023:       /* For an individual i, wav[i] gives the number of effective waves */
                   4024:       /* We compute the contribution to Likelihood of each effective transition
                   4025:         mw[mi][i] is real wave of the mi th effectve wave */
                   4026:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4027:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4028:         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  4029:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4030:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4031:       */
1.336     brouard  4032:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4033:       /* Wave varying (but not age varying) */
1.339     brouard  4034:        /* 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*\/ */
                   4035:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4036:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4037:        /* } */
1.340     brouard  4038:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4039:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4040:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4041:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4042:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4043:          }else{ /* fixed covariate */
1.345     brouard  4044:            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  4045:          }
1.339     brouard  4046:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4047:            cotvarvold=cotvarv;
                   4048:          }else{ /* A second product */
                   4049:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4050:          }
                   4051:          iposold=ipos;
1.340     brouard  4052:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4053:        }
1.339     brouard  4054:        /* for products of time varying to be done */
1.234     brouard  4055:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4056:          for (j=1;j<=nlstate+ndeath;j++){
                   4057:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4058:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4059:          }
1.336     brouard  4060: 
                   4061:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4062:        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  4063:        for(d=0; d<dh[mi][i]; d++){
                   4064:          newm=savm;
                   4065:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4066:          cov[2]=agexact;
                   4067:          if(nagesqr==1)
                   4068:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4069:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4070:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4071:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4072:          /*   else */
                   4073:          /*     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) *\/  */
                   4074:          /* } */
                   4075:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4076:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4077:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4078:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4079:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4080:            }else{ /* fixed covariate */
                   4081:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4082:            }
                   4083:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4084:              cotvarvold=cotvarv;
                   4085:            }else{ /* A second product */
                   4086:              cotvarv=cotvarv*cotvarvold;
                   4087:            }
                   4088:            iposold=ipos;
                   4089:            cov[ioffset+ipos]=cotvarv*agexact;
                   4090:            /* For products */
1.234     brouard  4091:          }
1.349     brouard  4092:          
1.234     brouard  4093:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4094:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4095:          savm=oldm;
                   4096:          oldm=newm;
                   4097:        } /* end mult */
                   4098:        
                   4099:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4100:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4101:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4102:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4103:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4104:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4105:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4106:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4107:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4108:                                 * -stepm/2 to stepm/2 .
                   4109:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4110:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4111:                                 */
1.234     brouard  4112:        s1=s[mw[mi][i]][i];
                   4113:        s2=s[mw[mi+1][i]][i];
                   4114:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4115:        /* bias bh is positive if real duration
                   4116:         * is higher than the multiple of stepm and negative otherwise.
                   4117:         */
                   4118:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4119:        if( s2 > nlstate){ 
                   4120:          /* i.e. if s2 is a death state and if the date of death is known 
                   4121:             then the contribution to the likelihood is the probability to 
                   4122:             die between last step unit time and current  step unit time, 
                   4123:             which is also equal to probability to die before dh 
                   4124:             minus probability to die before dh-stepm . 
                   4125:             In version up to 0.92 likelihood was computed
                   4126:             as if date of death was unknown. Death was treated as any other
                   4127:             health state: the date of the interview describes the actual state
                   4128:             and not the date of a change in health state. The former idea was
                   4129:             to consider that at each interview the state was recorded
                   4130:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4131:             introduced the exact date of death then we should have modified
                   4132:             the contribution of an exact death to the likelihood. This new
                   4133:             contribution is smaller and very dependent of the step unit
                   4134:             stepm. It is no more the probability to die between last interview
                   4135:             and month of death but the probability to survive from last
                   4136:             interview up to one month before death multiplied by the
                   4137:             probability to die within a month. Thanks to Chris
                   4138:             Jackson for correcting this bug.  Former versions increased
                   4139:             mortality artificially. The bad side is that we add another loop
                   4140:             which slows down the processing. The difference can be up to 10%
                   4141:             lower mortality.
                   4142:          */
                   4143:          /* If, at the beginning of the maximization mostly, the
                   4144:             cumulative probability or probability to be dead is
                   4145:             constant (ie = 1) over time d, the difference is equal to
                   4146:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4147:             s1 at precedent wave, to be dead a month before current
                   4148:             wave is equal to probability, being at state s1 at
                   4149:             precedent wave, to be dead at mont of the current
                   4150:             wave. Then the observed probability (that this person died)
                   4151:             is null according to current estimated parameter. In fact,
                   4152:             it should be very low but not zero otherwise the log go to
                   4153:             infinity.
                   4154:          */
1.183     brouard  4155: /* #ifdef INFINITYORIGINAL */
                   4156: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4157: /* #else */
                   4158: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4159: /*         lli=log(mytinydouble); */
                   4160: /*       else */
                   4161: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4162: /* #endif */
1.226     brouard  4163:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4164:          
1.226     brouard  4165:        } else if  ( s2==-1 ) { /* alive */
                   4166:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4167:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4168:          /*survp += out[s1][j]; */
                   4169:          lli= log(survp);
                   4170:        }
1.336     brouard  4171:        /* else if  (s2==-4) {  */
                   4172:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4173:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4174:        /*   lli= log(survp);  */
                   4175:        /* }  */
                   4176:        /* else if  (s2==-5) {  */
                   4177:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4178:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4179:        /*   lli= log(survp);  */
                   4180:        /* }  */
1.226     brouard  4181:        else{
                   4182:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4183:          /*  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 */
                   4184:        } 
                   4185:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4186:        /*if(lli ==000.0)*/
1.340     brouard  4187:        /* 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  4188:        ipmx +=1;
                   4189:        sw += weight[i];
                   4190:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4191:        /* if (lli < log(mytinydouble)){ */
                   4192:        /*   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); */
                   4193:        /*   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]); */
                   4194:        /* } */
                   4195:       } /* end of wave */
                   4196:     } /* end of individual */
                   4197:   }  else if(mle==2){
                   4198:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4199:       ioffset=2+nagesqr ;
                   4200:       for (k=1; k<=ncovf;k++)
                   4201:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4202:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4203:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4204:          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  4205:        }
1.226     brouard  4206:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4207:          for (j=1;j<=nlstate+ndeath;j++){
                   4208:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4209:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4210:          }
                   4211:        for(d=0; d<=dh[mi][i]; d++){
                   4212:          newm=savm;
                   4213:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4214:          cov[2]=agexact;
                   4215:          if(nagesqr==1)
                   4216:            cov[3]= agexact*agexact;
                   4217:          for (kk=1; kk<=cptcovage;kk++) {
                   4218:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4219:          }
                   4220:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4221:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4222:          savm=oldm;
                   4223:          oldm=newm;
                   4224:        } /* end mult */
                   4225:       
                   4226:        s1=s[mw[mi][i]][i];
                   4227:        s2=s[mw[mi+1][i]][i];
                   4228:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4229:        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 */
                   4230:        ipmx +=1;
                   4231:        sw += weight[i];
                   4232:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4233:       } /* end of wave */
                   4234:     } /* end of individual */
                   4235:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4236:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4237:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4238:       for(mi=1; mi<= wav[i]-1; mi++){
                   4239:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4240:          for (j=1;j<=nlstate+ndeath;j++){
                   4241:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4242:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4243:          }
                   4244:        for(d=0; d<dh[mi][i]; d++){
                   4245:          newm=savm;
                   4246:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4247:          cov[2]=agexact;
                   4248:          if(nagesqr==1)
                   4249:            cov[3]= agexact*agexact;
                   4250:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4251:            if(!FixedV[Tvar[Tage[kk]]])
                   4252:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4253:            else
1.341     brouard  4254:              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  4255:          }
                   4256:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4257:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4258:          savm=oldm;
                   4259:          oldm=newm;
                   4260:        } /* end mult */
                   4261:       
                   4262:        s1=s[mw[mi][i]][i];
                   4263:        s2=s[mw[mi+1][i]][i];
                   4264:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4265:        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 */
                   4266:        ipmx +=1;
                   4267:        sw += weight[i];
                   4268:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4269:       } /* end of wave */
                   4270:     } /* end of individual */
                   4271:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4272:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4273:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4274:       for(mi=1; mi<= wav[i]-1; mi++){
                   4275:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4276:          for (j=1;j<=nlstate+ndeath;j++){
                   4277:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4278:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4279:          }
                   4280:        for(d=0; d<dh[mi][i]; d++){
                   4281:          newm=savm;
                   4282:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4283:          cov[2]=agexact;
                   4284:          if(nagesqr==1)
                   4285:            cov[3]= agexact*agexact;
                   4286:          for (kk=1; kk<=cptcovage;kk++) {
                   4287:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4288:          }
1.126     brouard  4289:        
1.226     brouard  4290:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4291:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4292:          savm=oldm;
                   4293:          oldm=newm;
                   4294:        } /* end mult */
                   4295:       
                   4296:        s1=s[mw[mi][i]][i];
                   4297:        s2=s[mw[mi+1][i]][i];
                   4298:        if( s2 > nlstate){ 
                   4299:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4300:        } else if  ( s2==-1 ) { /* alive */
                   4301:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4302:            survp += out[s1][j];
                   4303:          lli= log(survp);
                   4304:        }else{
                   4305:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4306:        }
                   4307:        ipmx +=1;
                   4308:        sw += weight[i];
                   4309:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4310:        /* 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  4311:       } /* end of wave */
                   4312:     } /* end of individual */
                   4313:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4314:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4315:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4316:       for(mi=1; mi<= wav[i]-1; mi++){
                   4317:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4318:          for (j=1;j<=nlstate+ndeath;j++){
                   4319:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4320:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4321:          }
                   4322:        for(d=0; d<dh[mi][i]; d++){
                   4323:          newm=savm;
                   4324:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4325:          cov[2]=agexact;
                   4326:          if(nagesqr==1)
                   4327:            cov[3]= agexact*agexact;
                   4328:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4329:            if(!FixedV[Tvar[Tage[kk]]])
                   4330:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4331:            else
1.341     brouard  4332:              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  4333:          }
1.126     brouard  4334:        
1.226     brouard  4335:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4336:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4337:          savm=oldm;
                   4338:          oldm=newm;
                   4339:        } /* end mult */
                   4340:       
                   4341:        s1=s[mw[mi][i]][i];
                   4342:        s2=s[mw[mi+1][i]][i];
                   4343:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4344:        ipmx +=1;
                   4345:        sw += weight[i];
                   4346:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4347:        /*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]);*/
                   4348:       } /* end of wave */
                   4349:     } /* end of individual */
                   4350:   } /* End of if */
                   4351:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4352:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4353:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4354:   return -l;
1.126     brouard  4355: }
                   4356: 
                   4357: /*************** log-likelihood *************/
                   4358: double funcone( double *x)
                   4359: {
1.228     brouard  4360:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4361:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4362:   int ioffset=0;
1.339     brouard  4363:   int ipos=0,iposold=0,ncovv=0;
                   4364: 
1.340     brouard  4365:   double cotvarv, cotvarvold;
1.131     brouard  4366:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4367:   double **out;
                   4368:   double lli; /* Individual log likelihood */
                   4369:   double llt;
                   4370:   int s1, s2;
1.228     brouard  4371:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4372: 
1.126     brouard  4373:   double bbh, survp;
1.187     brouard  4374:   double agexact;
1.214     brouard  4375:   double agebegin, ageend;
1.126     brouard  4376:   /*extern weight */
                   4377:   /* We are differentiating ll according to initial status */
                   4378:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4379:   /*for(i=1;i<imx;i++) 
                   4380:     printf(" %d\n",s[4][i]);
                   4381:   */
                   4382:   cov[1]=1.;
                   4383: 
                   4384:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4385:   ioffset=0;
                   4386:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4387:     /* Computes the values of the ncovmodel covariates of the model
                   4388:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4389:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4390:        to be observed in j being in i according to the model.
                   4391:     */
1.243     brouard  4392:     /* ioffset=2+nagesqr+cptcovage; */
                   4393:     ioffset=2+nagesqr;
1.232     brouard  4394:     /* Fixed */
1.224     brouard  4395:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4396:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4397:     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  4398:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4399:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4400:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4401:       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  4402: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4403: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4404: /*    cov[2+6]=covar[2][i]; V2  */
                   4405: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4406: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4407: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4408: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4409: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4410: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4411:     }
1.336     brouard  4412:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4413:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4414:         has been calculated etc */
                   4415:       /* For an individual i, wav[i] gives the number of effective waves */
                   4416:       /* We compute the contribution to Likelihood of each effective transition
                   4417:         mw[mi][i] is real wave of the mi th effectve wave */
                   4418:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4419:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4420:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4421:       */
                   4422:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4423:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4424:     /*   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?)*\/ */
                   4425:     /* } */
1.231     brouard  4426:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4427:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4428:     /* } */
1.225     brouard  4429:     
1.233     brouard  4430: 
                   4431:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4432:       /* 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 */
                   4433:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4434:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4435:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4436:       /* } */
                   4437:       
                   4438:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4439:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4440:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4441:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4442:       /* We need the position of the time varying or product in the model */
                   4443:       /* 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 */            
                   4444:       /* TvarVV gives the variable name */
1.340     brouard  4445:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4446:       *      k=         1   2     3     4         5        6        7       8        9
                   4447:       *  varying            1     2                                 3       4        5
                   4448:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4449:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4450:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4451:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4452:       */
1.345     brouard  4453:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4454:        * 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  4455:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4456:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4457:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4458:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4459:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4460:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4461:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4462:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4463:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4464:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4465:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4466:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4467:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4468:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4469:        *                  12       13      14      15       16
                   4470:        *                    17        18         19        20         21
                   4471:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4472:        *                   2       3        4       6        7
                   4473:        *                     9         11          12        13         14            
                   4474:        * cptcovage=5+5 total of covariates with age 
                   4475:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4476:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4477:        *3 Tage[cptcovage] age*V3*V2=6  
                   4478:        *3                age*V2=12         13      14      15       16
                   4479:        *3                age*V6*V3=18      19    20   21
                   4480:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4481:        *     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
                   4482:        * 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
                   4483:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4484:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4485:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4486:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4487:        * 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
                   4488:        * Tvar=                {2, 3, 4, 6, 7,
                   4489:        *                       9, 10, 11, 12, 13, 14,
                   4490:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4491:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4492:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4493:        *                  2, 2, 2, 2, 2, 2,
                   4494:        * 3                3, 2, 2, 2, 2, 2,
                   4495:        *                  1, 1, 1, 1, 1, 
                   4496:        *                  3, 3, 3, 3, 3}
                   4497:        * 3                 2, 3, 3, 3, 3}
                   4498:        * 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
                   4499:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4500:        * 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}
                   4501:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4502:        * cptcovprod=11 (6+5)
                   4503:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4504:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4505:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4506:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4507:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4508:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4509:        * cptcovdageprod=5  for gnuplot printing
                   4510:        * cptcovprodvage=6 
                   4511:        * ncova=15           1        2       3       4       5
                   4512:        *                      6 7        8 9      10 11        12 13     14 15
                   4513:        * TvarA              2        3       4       6       7
                   4514:        *                      6 2        6 7       7 3          6 4       7 4
                   4515:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4516:        * ncovf            1     2      3
1.349     brouard  4517:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4518:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4519:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4520:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4521:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4522:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4523:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4524:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4525:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4526:        * 3 cptcovprodvage=6
                   4527:        * 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
                   4528:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4529:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
                   4530:        * TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
                   4531:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4532:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4533:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4534:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4535:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4536:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4537:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4538:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4539:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4540:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4541:        *                   2, 3, 4, 6, 7,
                   4542:        *                     6, 8, 9, 10, 11}
1.345     brouard  4543:        * TvarFind[itv]                        0      0       0
                   4544:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4545:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4546:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4547:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4548:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4549:        */
                   4550: 
1.349     brouard  4551:       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 */
                   4552:        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  4553:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4554:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4555:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4556:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4557:        }else{ /* fixed covariate */
1.345     brouard  4558:          /* 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  4559:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.340     brouard  4560:        }
1.339     brouard  4561:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4562:          cotvarvold=cotvarv;
                   4563:        }else{ /* A second product */
                   4564:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4565:        }
                   4566:        iposold=ipos;
1.340     brouard  4567:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4568:        /* For products */
                   4569:       }
                   4570:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4571:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4572:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4573:       /*       /\*           1  2   3      4      5                         *\/ */
                   4574:       /*       /\*itv           1                                           *\/ */
                   4575:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4576:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4577:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4578:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4579:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4580:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4581:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4582:       /*       /\* 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]); *\/ */
                   4583:       /* } */
1.232     brouard  4584:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4585:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4586:       /*       /\* 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]); *\/ */
                   4587:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4588:       /* } */
1.126     brouard  4589:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4590:        for (j=1;j<=nlstate+ndeath;j++){
                   4591:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4592:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4593:        }
1.214     brouard  4594:       
                   4595:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4596:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4597:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4598:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4599:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4600:          and mw[mi+1][i]. dh depends on stepm.*/
                   4601:        newm=savm;
1.247     brouard  4602:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4603:        cov[2]=agexact;
                   4604:        if(nagesqr==1)
                   4605:          cov[3]= agexact*agexact;
1.349     brouard  4606:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4607:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4608:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4609:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4610:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4611:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4612:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4613:          }else{ /* fixed covariate */
                   4614:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4615:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4616:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4617:          }
                   4618:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4619:            cotvarvold=cotvarv;
                   4620:          }else{ /* A second product */
                   4621:            /* printf("DEBUG * \n"); */
                   4622:            cotvarv=cotvarv*cotvarvold;
                   4623:          }
                   4624:          iposold=ipos;
                   4625:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4626:          cov[ioffset+ipos]=cotvarv*agexact;
                   4627:          /* For products */
1.242     brouard  4628:        }
1.349     brouard  4629: 
1.242     brouard  4630:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4631:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4632:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4633:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4634:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4635:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4636:        savm=oldm;
                   4637:        oldm=newm;
1.126     brouard  4638:       } /* end mult */
1.336     brouard  4639:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4640:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4641:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4642:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4643:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4644:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4645:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4646:         * probability in order to take into account the bias as a fraction of the way
                   4647:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4648:                                 * -stepm/2 to stepm/2 .
                   4649:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4650:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4651:                                 */
1.126     brouard  4652:       s1=s[mw[mi][i]][i];
                   4653:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4654:       /* if(s2==-1){ */
1.268     brouard  4655:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4656:       /*       /\* exit(1); *\/ */
                   4657:       /* } */
1.126     brouard  4658:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4659:       /* bias is positive if real duration
                   4660:        * is higher than the multiple of stepm and negative otherwise.
                   4661:        */
                   4662:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4663:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4664:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4665:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4666:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4667:        lli= log(survp);
1.126     brouard  4668:       }else if (mle==1){
1.242     brouard  4669:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4670:       } else if(mle==2){
1.242     brouard  4671:        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  4672:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4673:        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  4674:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4675:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4676:       } else{  /* mle=0 back to 1 */
1.242     brouard  4677:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4678:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4679:       } /* End of if */
                   4680:       ipmx +=1;
                   4681:       sw += weight[i];
                   4682:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4683:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4684:       /* 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  4685:       if(globpr){
1.246     brouard  4686:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4687:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4688:                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  4689:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4690:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4691:        /* %11.6f %11.6f %11.6f ", \ */
                   4692:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4693:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4694:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4695:          llt +=ll[k]*gipmx/gsw;
                   4696:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4697:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4698:        }
1.343     brouard  4699:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4700:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4701:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4702:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4703:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4704:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4705:        }
                   4706:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4707:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4708:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4709:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4710:            /* printf(" %g",cov[ioffset+ipos]); */
                   4711:          }else{
                   4712:            fprintf(ficresilk,"*");
                   4713:            /* printf("*"); */
1.342     brouard  4714:          }
1.343     brouard  4715:          iposold=ipos;
                   4716:        }
1.349     brouard  4717:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4718:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4719:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4720:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4721:        /*   }else{ */
                   4722:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4723:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4724:        /*   } */
                   4725:        /* } */
                   4726:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4727:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4728:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4729:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4730:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4731:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4732:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4733:          }else{ /* fixed covariate */
                   4734:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4735:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4736:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4737:          }
                   4738:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4739:            cotvarvold=cotvarv;
                   4740:          }else{ /* A second product */
                   4741:            /* printf("DEBUG * \n"); */
                   4742:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4743:          }
1.349     brouard  4744:          cotvarv=cotvarv*agexact;
                   4745:          fprintf(ficresilk," %g*age",cotvarv);
                   4746:          iposold=ipos;
                   4747:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4748:          cov[ioffset+ipos]=cotvarv;
                   4749:          /* For products */
1.343     brouard  4750:        }
                   4751:        /* printf("\n"); */
1.342     brouard  4752:        /* } /\*  End debugILK *\/ */
                   4753:        fprintf(ficresilk,"\n");
                   4754:       } /* End if globpr */
1.335     brouard  4755:     } /* end of wave */
                   4756:   } /* end of individual */
                   4757:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4758: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4759:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4760:   if(globpr==0){ /* First time we count the contributions and weights */
                   4761:     gipmx=ipmx;
                   4762:     gsw=sw;
                   4763:   }
1.343     brouard  4764:   return -l;
1.126     brouard  4765: }
                   4766: 
                   4767: 
                   4768: /*************** function likelione ***********/
1.292     brouard  4769: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4770: {
                   4771:   /* This routine should help understanding what is done with 
                   4772:      the selection of individuals/waves and
                   4773:      to check the exact contribution to the likelihood.
                   4774:      Plotting could be done.
1.342     brouard  4775:   */
                   4776:   void pstamp(FILE *ficres);
1.343     brouard  4777:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4778: 
                   4779:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4780:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4781:     strcat(fileresilk,fileresu);
1.126     brouard  4782:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4783:       printf("Problem with resultfile: %s\n", fileresilk);
                   4784:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4785:     }
1.342     brouard  4786:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4787:     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");
                   4788:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4789:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4790:     for(k=1; k<=nlstate; k++) 
                   4791:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4792:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4793: 
                   4794:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4795:       for(kf=1;kf <= ncovf; kf++){
                   4796:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4797:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4798:       }
                   4799:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4800:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4801:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4802:          /* printf(" %d",ipos); */
                   4803:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4804:        }else{
                   4805:          /* printf("*"); */
                   4806:          fprintf(ficresilk,"*");
1.343     brouard  4807:        }
1.342     brouard  4808:        iposold=ipos;
                   4809:       }
                   4810:       for (kk=1; kk<=cptcovage;kk++) {
                   4811:        if(!FixedV[Tvar[Tage[kk]]]){
                   4812:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4813:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4814:        }else{
                   4815:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4816:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4817:        }
                   4818:       }
                   4819:     /* } /\* End if debugILK *\/ */
                   4820:     /* printf("\n"); */
                   4821:     fprintf(ficresilk,"\n");
                   4822:   } /* End glogpri */
1.126     brouard  4823: 
1.292     brouard  4824:   *fretone=(*func)(p);
1.126     brouard  4825:   if(*globpri !=0){
                   4826:     fclose(ficresilk);
1.205     brouard  4827:     if (mle ==0)
                   4828:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4829:     else if(mle >=1)
                   4830:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4831:     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  4832:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4833:       
1.207     brouard  4834:     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  4835: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4836:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4837: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4838:     
                   4839:     for (k=1; k<= nlstate ; k++) {
                   4840:       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 \
                   4841: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4842:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350   ! brouard  4843:         kvar=Tvar[TvarFind[kf]];  /* variable */
        !          4844:         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]]);
        !          4845:         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);
        !          4846:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4847:       }
                   4848:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4849:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4850:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4851:        /* 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]); */
                   4852:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4853:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4854:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4855:          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)  */
                   4856:            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> \
                   4857: <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);
                   4858:          } /* End only for dummies time varying (single?) */
                   4859:        }else{ /* Useless product */
                   4860:          /* printf("*"); */
                   4861:          /* fprintf(ficresilk,"*"); */ 
                   4862:        }
                   4863:        iposold=ipos;
                   4864:       } /* For each time varying covariate */
                   4865:     } /* End loop on states */
                   4866: 
                   4867: /*     if(debugILK){ */
                   4868: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4869: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4870: /*     for (k=1; k<= nlstate ; k++) { */
                   4871: /*       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> \ */
                   4872: /* <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]]); */
                   4873: /*     } */
                   4874: /*       } */
                   4875: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4876: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4877: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4878: /*     /\* 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]); *\/ */
                   4879: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4880: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4881: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4882: /*       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)  *\/ */
                   4883: /*         for (k=1; k<= nlstate ; k++) { */
                   4884: /*           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> \ */
                   4885: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4886: /*         } /\* End state *\/ */
                   4887: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4888: /*     }else{ /\* Useless product *\/ */
                   4889: /*       /\* printf("*"); *\/ */
                   4890: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4891: /*     } */
                   4892: /*     iposold=ipos; */
                   4893: /*       } /\* For each time varying covariate *\/ */
                   4894: /*     }/\* End debugILK *\/ */
1.207     brouard  4895:     fflush(fichtm);
1.343     brouard  4896:   }/* End globpri */
1.126     brouard  4897:   return;
                   4898: }
                   4899: 
                   4900: 
                   4901: /*********** Maximum Likelihood Estimation ***************/
                   4902: 
                   4903: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4904: {
1.319     brouard  4905:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4906:   double **xi;
                   4907:   double fret;
                   4908:   double fretone; /* Only one call to likelihood */
                   4909:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4910: 
                   4911: #ifdef NLOPT
                   4912:   int creturn;
                   4913:   nlopt_opt opt;
                   4914:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4915:   double *lb;
                   4916:   double minf; /* the minimum objective value, upon return */
                   4917:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4918:   myfunc_data dinst, *d = &dinst;
                   4919: #endif
                   4920: 
                   4921: 
1.126     brouard  4922:   xi=matrix(1,npar,1,npar);
                   4923:   for (i=1;i<=npar;i++)
                   4924:     for (j=1;j<=npar;j++)
                   4925:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4926:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4927:   strcpy(filerespow,"POW_"); 
1.126     brouard  4928:   strcat(filerespow,fileres);
                   4929:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4930:     printf("Problem with resultfile: %s\n", filerespow);
                   4931:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4932:   }
                   4933:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4934:   for (i=1;i<=nlstate;i++)
                   4935:     for(j=1;j<=nlstate+ndeath;j++)
                   4936:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4937:   fprintf(ficrespow,"\n");
1.162     brouard  4938: #ifdef POWELL
1.319     brouard  4939: #ifdef LINMINORIGINAL
                   4940: #else /* LINMINORIGINAL */
                   4941:   
                   4942:   flatdir=ivector(1,npar); 
                   4943:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4944: #endif /*LINMINORIGINAL */
                   4945: 
                   4946: #ifdef FLATSUP
                   4947:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4948:   /* reorganizing p by suppressing flat directions */
                   4949:   for(i=1, jk=1; i <=nlstate; i++){
                   4950:     for(k=1; k <=(nlstate+ndeath); k++){
                   4951:       if (k != i) {
                   4952:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4953:         if(flatdir[jk]==1){
                   4954:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4955:         }
                   4956:         for(j=1; j <=ncovmodel; j++){
                   4957:           printf("%12.7f ",p[jk]);
                   4958:           jk++; 
                   4959:         }
                   4960:         printf("\n");
                   4961:       }
                   4962:     }
                   4963:   }
                   4964: /* skipping */
                   4965:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4966:   for(i=1, jk=1, jkk=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 jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4972:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4973:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4974:             /*q[jjk]=p[jk];*/
                   4975:           }
                   4976:         }else{
                   4977:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4978:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4979:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4980:             /*q[jjk]=p[jk];*/
                   4981:           }
                   4982:         }
                   4983:         printf("\n");
                   4984:       }
                   4985:       fflush(stdout);
                   4986:     }
                   4987:   }
                   4988:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4989: #else  /* FLATSUP */
1.126     brouard  4990:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4991: #endif  /* FLATSUP */
                   4992: 
                   4993: #ifdef LINMINORIGINAL
                   4994: #else
                   4995:       free_ivector(flatdir,1,npar); 
                   4996: #endif  /* LINMINORIGINAL*/
                   4997: #endif /* POWELL */
1.126     brouard  4998: 
1.162     brouard  4999: #ifdef NLOPT
                   5000: #ifdef NEWUOA
                   5001:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5002: #else
                   5003:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5004: #endif
                   5005:   lb=vector(0,npar-1);
                   5006:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5007:   nlopt_set_lower_bounds(opt, lb);
                   5008:   nlopt_set_initial_step1(opt, 0.1);
                   5009:   
                   5010:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5011:   d->function = func;
                   5012:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5013:   nlopt_set_min_objective(opt, myfunc, d);
                   5014:   nlopt_set_xtol_rel(opt, ftol);
                   5015:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5016:     printf("nlopt failed! %d\n",creturn); 
                   5017:   }
                   5018:   else {
                   5019:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5020:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5021:     iter=1; /* not equal */
                   5022:   }
                   5023:   nlopt_destroy(opt);
                   5024: #endif
1.319     brouard  5025: #ifdef FLATSUP
                   5026:   /* npared = npar -flatd/ncovmodel; */
                   5027:   /* xired= matrix(1,npared,1,npared); */
                   5028:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5029:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5030:   /* free_matrix(xire,1,npared,1,npared); */
                   5031: #else  /* FLATSUP */
                   5032: #endif /* FLATSUP */
1.126     brouard  5033:   free_matrix(xi,1,npar,1,npar);
                   5034:   fclose(ficrespow);
1.203     brouard  5035:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5036:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5037:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5038: 
                   5039: }
                   5040: 
                   5041: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5042: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5043: {
                   5044:   double  **a,**y,*x,pd;
1.203     brouard  5045:   /* double **hess; */
1.164     brouard  5046:   int i, j;
1.126     brouard  5047:   int *indx;
                   5048: 
                   5049:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5050:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5051:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5052:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5053:   double gompertz(double p[]);
1.203     brouard  5054:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5055: 
                   5056:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5057:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5058:   for (i=1;i<=npar;i++){
1.203     brouard  5059:     printf("%d-",i);fflush(stdout);
                   5060:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5061:    
                   5062:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5063:     
                   5064:     /*  printf(" %f ",p[i]);
                   5065:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5066:   }
                   5067:   
                   5068:   for (i=1;i<=npar;i++) {
                   5069:     for (j=1;j<=npar;j++)  {
                   5070:       if (j>i) { 
1.203     brouard  5071:        printf(".%d-%d",i,j);fflush(stdout);
                   5072:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5073:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5074:        
                   5075:        hess[j][i]=hess[i][j];    
                   5076:        /*printf(" %lf ",hess[i][j]);*/
                   5077:       }
                   5078:     }
                   5079:   }
                   5080:   printf("\n");
                   5081:   fprintf(ficlog,"\n");
                   5082: 
                   5083:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5084:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5085:   
                   5086:   a=matrix(1,npar,1,npar);
                   5087:   y=matrix(1,npar,1,npar);
                   5088:   x=vector(1,npar);
                   5089:   indx=ivector(1,npar);
                   5090:   for (i=1;i<=npar;i++)
                   5091:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5092:   ludcmp(a,npar,indx,&pd);
                   5093: 
                   5094:   for (j=1;j<=npar;j++) {
                   5095:     for (i=1;i<=npar;i++) x[i]=0;
                   5096:     x[j]=1;
                   5097:     lubksb(a,npar,indx,x);
                   5098:     for (i=1;i<=npar;i++){ 
                   5099:       matcov[i][j]=x[i];
                   5100:     }
                   5101:   }
                   5102: 
                   5103:   printf("\n#Hessian matrix#\n");
                   5104:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5105:   for (i=1;i<=npar;i++) { 
                   5106:     for (j=1;j<=npar;j++) { 
1.203     brouard  5107:       printf("%.6e ",hess[i][j]);
                   5108:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5109:     }
                   5110:     printf("\n");
                   5111:     fprintf(ficlog,"\n");
                   5112:   }
                   5113: 
1.203     brouard  5114:   /* printf("\n#Covariance matrix#\n"); */
                   5115:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5116:   /* for (i=1;i<=npar;i++) {  */
                   5117:   /*   for (j=1;j<=npar;j++) {  */
                   5118:   /*     printf("%.6e ",matcov[i][j]); */
                   5119:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5120:   /*   } */
                   5121:   /*   printf("\n"); */
                   5122:   /*   fprintf(ficlog,"\n"); */
                   5123:   /* } */
                   5124: 
1.126     brouard  5125:   /* Recompute Inverse */
1.203     brouard  5126:   /* for (i=1;i<=npar;i++) */
                   5127:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5128:   /* ludcmp(a,npar,indx,&pd); */
                   5129: 
                   5130:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5131: 
                   5132:   /* for (j=1;j<=npar;j++) { */
                   5133:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5134:   /*   x[j]=1; */
                   5135:   /*   lubksb(a,npar,indx,x); */
                   5136:   /*   for (i=1;i<=npar;i++){  */
                   5137:   /*     y[i][j]=x[i]; */
                   5138:   /*     printf("%.3e ",y[i][j]); */
                   5139:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5140:   /*   } */
                   5141:   /*   printf("\n"); */
                   5142:   /*   fprintf(ficlog,"\n"); */
                   5143:   /* } */
                   5144: 
                   5145:   /* Verifying the inverse matrix */
                   5146: #ifdef DEBUGHESS
                   5147:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5148: 
1.203     brouard  5149:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5150:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5151: 
                   5152:   for (j=1;j<=npar;j++) {
                   5153:     for (i=1;i<=npar;i++){ 
1.203     brouard  5154:       printf("%.2f ",y[i][j]);
                   5155:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5156:     }
                   5157:     printf("\n");
                   5158:     fprintf(ficlog,"\n");
                   5159:   }
1.203     brouard  5160: #endif
1.126     brouard  5161: 
                   5162:   free_matrix(a,1,npar,1,npar);
                   5163:   free_matrix(y,1,npar,1,npar);
                   5164:   free_vector(x,1,npar);
                   5165:   free_ivector(indx,1,npar);
1.203     brouard  5166:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5167: 
                   5168: 
                   5169: }
                   5170: 
                   5171: /*************** hessian matrix ****************/
                   5172: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5173: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5174:   int i;
                   5175:   int l=1, lmax=20;
1.203     brouard  5176:   double k1,k2, res, fx;
1.132     brouard  5177:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5178:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5179:   int k=0,kmax=10;
                   5180:   double l1;
                   5181: 
                   5182:   fx=func(x);
                   5183:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5184:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5185:     l1=pow(10,l);
                   5186:     delts=delt;
                   5187:     for(k=1 ; k <kmax; k=k+1){
                   5188:       delt = delta*(l1*k);
                   5189:       p2[theta]=x[theta] +delt;
1.145     brouard  5190:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5191:       p2[theta]=x[theta]-delt;
                   5192:       k2=func(p2)-fx;
                   5193:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5194:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5195:       
1.203     brouard  5196: #ifdef DEBUGHESSII
1.126     brouard  5197:       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);
                   5198:       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);
                   5199: #endif
                   5200:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5201:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5202:        k=kmax;
                   5203:       }
                   5204:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5205:        k=kmax; l=lmax*10;
1.126     brouard  5206:       }
                   5207:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5208:        delts=delt;
                   5209:       }
1.203     brouard  5210:     } /* End loop k */
1.126     brouard  5211:   }
                   5212:   delti[theta]=delts;
                   5213:   return res; 
                   5214:   
                   5215: }
                   5216: 
1.203     brouard  5217: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5218: {
                   5219:   int i;
1.164     brouard  5220:   int l=1, lmax=20;
1.126     brouard  5221:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5222:   double p2[MAXPARM+1];
1.203     brouard  5223:   int k, kmax=1;
                   5224:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5225: 
                   5226:   int firstime=0;
1.203     brouard  5227:   
1.126     brouard  5228:   fx=func(x);
1.203     brouard  5229:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5230:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5231:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5232:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5233:     k1=func(p2)-fx;
                   5234:   
1.203     brouard  5235:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5236:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5237:     k2=func(p2)-fx;
                   5238:   
1.203     brouard  5239:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5240:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5241:     k3=func(p2)-fx;
                   5242:   
1.203     brouard  5243:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5244:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5245:     k4=func(p2)-fx;
1.203     brouard  5246:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5247:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5248:       firstime=1;
1.203     brouard  5249:       kmax=kmax+10;
1.208     brouard  5250:     }
                   5251:     if(kmax >=10 || firstime ==1){
1.246     brouard  5252:       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);
                   5253:       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  5254:       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);
                   5255:       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);
                   5256:     }
                   5257: #ifdef DEBUGHESSIJ
                   5258:     v1=hess[thetai][thetai];
                   5259:     v2=hess[thetaj][thetaj];
                   5260:     cv12=res;
                   5261:     /* Computing eigen value of Hessian matrix */
                   5262:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5263:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5264:     if ((lc2 <0) || (lc1 <0) ){
                   5265:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5266:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5267:       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);
                   5268:       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);
                   5269:     }
1.126     brouard  5270: #endif
                   5271:   }
                   5272:   return res;
                   5273: }
                   5274: 
1.203     brouard  5275:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5276: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5277: /* { */
                   5278: /*   int i; */
                   5279: /*   int l=1, lmax=20; */
                   5280: /*   double k1,k2,k3,k4,res,fx; */
                   5281: /*   double p2[MAXPARM+1]; */
                   5282: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5283: /*   int k=0,kmax=10; */
                   5284: /*   double l1; */
                   5285:   
                   5286: /*   fx=func(x); */
                   5287: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5288: /*     l1=pow(10,l); */
                   5289: /*     delts=delt; */
                   5290: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5291: /*       delt = delti*(l1*k); */
                   5292: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5293: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5294: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5295: /*       k1=func(p2)-fx; */
                   5296:       
                   5297: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5298: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5299: /*       k2=func(p2)-fx; */
                   5300:       
                   5301: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5302: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5303: /*       k3=func(p2)-fx; */
                   5304:       
                   5305: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5306: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5307: /*       k4=func(p2)-fx; */
                   5308: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5309: /* #ifdef DEBUGHESSIJ */
                   5310: /*       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); */
                   5311: /*       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); */
                   5312: /* #endif */
                   5313: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5314: /*     k=kmax; */
                   5315: /*       } */
                   5316: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5317: /*     k=kmax; l=lmax*10; */
                   5318: /*       } */
                   5319: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5320: /*     delts=delt; */
                   5321: /*       } */
                   5322: /*     } /\* End loop k *\/ */
                   5323: /*   } */
                   5324: /*   delti[theta]=delts; */
                   5325: /*   return res;  */
                   5326: /* } */
                   5327: 
                   5328: 
1.126     brouard  5329: /************** Inverse of matrix **************/
                   5330: void ludcmp(double **a, int n, int *indx, double *d) 
                   5331: { 
                   5332:   int i,imax,j,k; 
                   5333:   double big,dum,sum,temp; 
                   5334:   double *vv; 
                   5335:  
                   5336:   vv=vector(1,n); 
                   5337:   *d=1.0; 
                   5338:   for (i=1;i<=n;i++) { 
                   5339:     big=0.0; 
                   5340:     for (j=1;j<=n;j++) 
                   5341:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5342:     if (big == 0.0){
                   5343:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5344:       for (j=1;j<=n;j++) {
                   5345:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5346:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5347:       }
                   5348:       fflush(ficlog);
                   5349:       fclose(ficlog);
                   5350:       nrerror("Singular matrix in routine ludcmp"); 
                   5351:     }
1.126     brouard  5352:     vv[i]=1.0/big; 
                   5353:   } 
                   5354:   for (j=1;j<=n;j++) { 
                   5355:     for (i=1;i<j;i++) { 
                   5356:       sum=a[i][j]; 
                   5357:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5358:       a[i][j]=sum; 
                   5359:     } 
                   5360:     big=0.0; 
                   5361:     for (i=j;i<=n;i++) { 
                   5362:       sum=a[i][j]; 
                   5363:       for (k=1;k<j;k++) 
                   5364:        sum -= a[i][k]*a[k][j]; 
                   5365:       a[i][j]=sum; 
                   5366:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5367:        big=dum; 
                   5368:        imax=i; 
                   5369:       } 
                   5370:     } 
                   5371:     if (j != imax) { 
                   5372:       for (k=1;k<=n;k++) { 
                   5373:        dum=a[imax][k]; 
                   5374:        a[imax][k]=a[j][k]; 
                   5375:        a[j][k]=dum; 
                   5376:       } 
                   5377:       *d = -(*d); 
                   5378:       vv[imax]=vv[j]; 
                   5379:     } 
                   5380:     indx[j]=imax; 
                   5381:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5382:     if (j != n) { 
                   5383:       dum=1.0/(a[j][j]); 
                   5384:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5385:     } 
                   5386:   } 
                   5387:   free_vector(vv,1,n);  /* Doesn't work */
                   5388: ;
                   5389: } 
                   5390: 
                   5391: void lubksb(double **a, int n, int *indx, double b[]) 
                   5392: { 
                   5393:   int i,ii=0,ip,j; 
                   5394:   double sum; 
                   5395:  
                   5396:   for (i=1;i<=n;i++) { 
                   5397:     ip=indx[i]; 
                   5398:     sum=b[ip]; 
                   5399:     b[ip]=b[i]; 
                   5400:     if (ii) 
                   5401:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5402:     else if (sum) ii=i; 
                   5403:     b[i]=sum; 
                   5404:   } 
                   5405:   for (i=n;i>=1;i--) { 
                   5406:     sum=b[i]; 
                   5407:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5408:     b[i]=sum/a[i][i]; 
                   5409:   } 
                   5410: } 
                   5411: 
                   5412: void pstamp(FILE *fichier)
                   5413: {
1.196     brouard  5414:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5415: }
                   5416: 
1.297     brouard  5417: void date2dmy(double date,double *day, double *month, double *year){
                   5418:   double yp=0., yp1=0., yp2=0.;
                   5419:   
                   5420:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5421:                        fractional in yp1 */
                   5422:   *year=yp;
                   5423:   yp2=modf((yp1*12),&yp);
                   5424:   *month=yp;
                   5425:   yp1=modf((yp2*30.5),&yp);
                   5426:   *day=yp;
                   5427:   if(*day==0) *day=1;
                   5428:   if(*month==0) *month=1;
                   5429: }
                   5430: 
1.253     brouard  5431: 
                   5432: 
1.126     brouard  5433: /************ Frequencies ********************/
1.251     brouard  5434: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5435:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5436:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5437: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5438:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5439:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5440:   int iind=0, iage=0;
                   5441:   int mi; /* Effective wave */
                   5442:   int first;
                   5443:   double ***freq; /* Frequencies */
1.268     brouard  5444:   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 */
                   5445:   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  5446:   double *meanq, *stdq, *idq;
1.226     brouard  5447:   double **meanqt;
                   5448:   double *pp, **prop, *posprop, *pospropt;
                   5449:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5450:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5451:   double agebegin, ageend;
                   5452:     
                   5453:   pp=vector(1,nlstate);
1.251     brouard  5454:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5455:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5456:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5457:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5458:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5459:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5460:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5461:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5462:   strcpy(fileresp,"P_");
                   5463:   strcat(fileresp,fileresu);
                   5464:   /*strcat(fileresphtm,fileresu);*/
                   5465:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5466:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5467:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5468:     exit(0);
                   5469:   }
1.240     brouard  5470:   
1.226     brouard  5471:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5472:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5473:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5474:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5475:     fflush(ficlog);
                   5476:     exit(70); 
                   5477:   }
                   5478:   else{
                   5479:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5480: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5481: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5482:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5483:   }
1.319     brouard  5484:   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  5485:   
1.226     brouard  5486:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5487:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5488:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5489:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5490:     fflush(ficlog);
                   5491:     exit(70); 
1.240     brouard  5492:   } else{
1.226     brouard  5493:     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  5494: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5495: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5496:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5497:   }
1.319     brouard  5498:   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  5499:   
1.253     brouard  5500:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5501:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5502:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5503:   j1=0;
1.126     brouard  5504:   
1.227     brouard  5505:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5506:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5507:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5508:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5509:   
                   5510:   
1.226     brouard  5511:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5512:      reference=low_education V1=0,V2=0
                   5513:      med_educ                V1=1 V2=0, 
                   5514:      high_educ               V1=0 V2=1
1.330     brouard  5515:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5516:   */
1.249     brouard  5517:   dateintsum=0;
                   5518:   k2cpt=0;
                   5519: 
1.253     brouard  5520:   if(cptcoveff == 0 )
1.265     brouard  5521:     nl=1;  /* Constant and age model only */
1.253     brouard  5522:   else
                   5523:     nl=2;
1.265     brouard  5524: 
                   5525:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5526:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5527:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5528:    *     freq[s1][s2][iage] =0.
                   5529:    *     Loop on iind
                   5530:    *       ++freq[s1][s2][iage] weighted
                   5531:    *     end iind
                   5532:    *     if covariate and j!0
                   5533:    *       headers Variable on one line
                   5534:    *     endif cov j!=0
                   5535:    *     header of frequency table by age
                   5536:    *     Loop on age
                   5537:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5538:    *       pos+=freq[s1][s2][iage] weighted
                   5539:    *       Loop on s1 initial state
                   5540:    *         fprintf(ficresp
                   5541:    *       end s1
                   5542:    *     end age
                   5543:    *     if j!=0 computes starting values
                   5544:    *     end compute starting values
                   5545:    *   end j1
                   5546:    * end nl 
                   5547:    */
1.253     brouard  5548:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5549:     if(nj==1)
                   5550:       j=0;  /* First pass for the constant */
1.265     brouard  5551:     else{
1.335     brouard  5552:       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  5553:     }
1.251     brouard  5554:     first=1;
1.332     brouard  5555:     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  5556:       posproptt=0.;
1.330     brouard  5557:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5558:        scanf("%d", i);*/
                   5559:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5560:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5561:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5562:            freq[i][s2][m]=0;
1.251     brouard  5563:       
                   5564:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5565:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5566:          prop[i][m]=0;
                   5567:        posprop[i]=0;
                   5568:        pospropt[i]=0;
                   5569:       }
1.283     brouard  5570:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5571:         idq[z1]=0.;
                   5572:         meanq[z1]=0.;
                   5573:         stdq[z1]=0.;
1.283     brouard  5574:       }
                   5575:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5576:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5577:       /*         meanqt[m][z1]=0.; */
                   5578:       /*       } */
                   5579:       /* }       */
1.251     brouard  5580:       /* dateintsum=0; */
                   5581:       /* k2cpt=0; */
                   5582:       
1.265     brouard  5583:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5584:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5585:        bool=1;
                   5586:        if(j !=0){
                   5587:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5588:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5589:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5590:                /* if(Tvaraff[z1] ==-20){ */
                   5591:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5592:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5593:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5594:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5595:                /* 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); */
                   5596:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5597:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5598:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5599:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5600:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5601:                  /* 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", */
                   5602:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5603:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5604:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5605:                } /* Onlyf fixed */
                   5606:              } /* end z1 */
1.335     brouard  5607:            } /* cptcoveff > 0 */
1.251     brouard  5608:          } /* end any */
                   5609:        }/* end j==0 */
1.265     brouard  5610:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5611:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5612:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5613:            m=mw[mi][iind];
                   5614:            if(j!=0){
                   5615:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5616:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5617:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5618:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5619:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5620:                    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  5621:                                                                                      value is -1, we don't select. It differs from the 
                   5622:                                                                                      constant and age model which counts them. */
                   5623:                      bool=0; /* not selected */
                   5624:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5625:                    /* i1=Tvaraff[z1]; */
                   5626:                    /* i2=TnsdVar[i1]; */
                   5627:                    /* i3=nbcode[i1][i2]; */
                   5628:                    /* i4=covar[i1][iind]; */
                   5629:                    /* if(i4 != i3){ */
                   5630:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5631:                      bool=0;
                   5632:                    }
                   5633:                  }
                   5634:                }
                   5635:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5636:            } /* end j==0 */
                   5637:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5638:            if(bool==1){ /*Selected */
1.251     brouard  5639:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5640:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5641:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5642:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5643:              if(m >=firstpass && m <=lastpass){
                   5644:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5645:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5646:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5647:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5648:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5649:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5650:                if (m<lastpass) {
                   5651:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5652:                  /*   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]); */
                   5653:                  if(s[m][iind]==-1)
                   5654:                    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.));
                   5655:                  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  5656:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5657:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5658:                      idq[z1]=idq[z1]+weight[iind];
                   5659:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5660:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5661:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5662:                    }
1.284     brouard  5663:                  }
1.251     brouard  5664:                  /* if((int)agev[m][iind] == 55) */
                   5665:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5666:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5667:                  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  5668:                }
1.251     brouard  5669:              } /* end if between passes */  
                   5670:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5671:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5672:                k2cpt++;
                   5673:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5674:              }
1.251     brouard  5675:            }else{
                   5676:              bool=1;
                   5677:            }/* end bool 2 */
                   5678:          } /* end m */
1.284     brouard  5679:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5680:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5681:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5682:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5683:          /* } */
1.251     brouard  5684:        } /* end bool */
                   5685:       } /* end iind = 1 to imx */
1.319     brouard  5686:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5687:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5688:       
                   5689:       
                   5690:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5691:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5692:         pstamp(ficresp);
1.335     brouard  5693:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5694:         pstamp(ficresp);
1.251     brouard  5695:        printf( "\n#********** Variable "); 
                   5696:        fprintf(ficresp, "\n#********** Variable "); 
                   5697:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5698:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5699:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5700:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5701:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5702:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5703:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5704:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5705:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5706:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5707:          }else{
1.330     brouard  5708:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5709:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5710:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5711:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5712:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5713:          }
                   5714:        }
                   5715:        printf( "**********\n#");
                   5716:        fprintf(ficresp, "**********\n#");
                   5717:        fprintf(ficresphtm, "**********</h3>\n");
                   5718:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5719:        fprintf(ficlog, "**********\n");
                   5720:       }
1.284     brouard  5721:       /*
                   5722:        Printing means of quantitative variables if any
                   5723:       */
                   5724:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5725:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5726:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5727:        if(weightopt==1){
                   5728:          printf(" Weighted mean and standard deviation of");
                   5729:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5730:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5731:        }
1.311     brouard  5732:        /* mu = \frac{w x}{\sum w}
                   5733:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5734:        */
                   5735:        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]));
                   5736:        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]));
                   5737:        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  5738:       }
                   5739:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5740:       /*       for(m=1;m<=lastpass;m++){ */
                   5741:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5742:       /*   } */
                   5743:       /* } */
1.283     brouard  5744: 
1.251     brouard  5745:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5746:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5747:         fprintf(ficresp, " Age");
1.335     brouard  5748:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5749:          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]]);
                   5750:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5751:        }
1.251     brouard  5752:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5753:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5754:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5755:       }
1.335     brouard  5756:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5757:       fprintf(ficresphtm, "\n");
                   5758:       
                   5759:       /* Header of frequency table by age */
                   5760:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5761:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5762:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5763:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5764:          if(s2!=0 && m!=0)
                   5765:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5766:        }
1.226     brouard  5767:       }
1.251     brouard  5768:       fprintf(ficresphtmfr, "\n");
                   5769:     
                   5770:       /* For each age */
                   5771:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5772:        fprintf(ficresphtm,"<tr>");
                   5773:        if(iage==iagemax+1){
                   5774:          fprintf(ficlog,"1");
                   5775:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5776:        }else if(iage==iagemax+2){
                   5777:          fprintf(ficlog,"0");
                   5778:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5779:        }else if(iage==iagemax+3){
                   5780:          fprintf(ficlog,"Total");
                   5781:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5782:        }else{
1.240     brouard  5783:          if(first==1){
1.251     brouard  5784:            first=0;
                   5785:            printf("See log file for details...\n");
                   5786:          }
                   5787:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5788:          fprintf(ficlog,"Age %d", iage);
                   5789:        }
1.265     brouard  5790:        for(s1=1; s1 <=nlstate ; s1++){
                   5791:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5792:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5793:        }
1.265     brouard  5794:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5795:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5796:            pos += freq[s1][m][iage];
                   5797:          if(pp[s1]>=1.e-10){
1.251     brouard  5798:            if(first==1){
1.265     brouard  5799:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5800:            }
1.265     brouard  5801:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5802:          }else{
                   5803:            if(first==1)
1.265     brouard  5804:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5805:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5806:          }
                   5807:        }
                   5808:       
1.265     brouard  5809:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5810:          /* posprop[s1]=0; */
                   5811:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5812:            pp[s1] += freq[s1][m][iage];
                   5813:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5814:       
                   5815:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5816:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5817:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5818:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5819:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5820:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5821:        }
                   5822:        
                   5823:        /* Writing ficresp */
1.335     brouard  5824:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5825:           if( iage <= iagemax){
                   5826:            fprintf(ficresp," %d",iage);
                   5827:           }
                   5828:         }else if( nj==2){
                   5829:           if( iage <= iagemax){
                   5830:            fprintf(ficresp," %d",iage);
1.335     brouard  5831:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5832:           }
1.240     brouard  5833:        }
1.265     brouard  5834:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5835:          if(pos>=1.e-5){
1.251     brouard  5836:            if(first==1)
1.265     brouard  5837:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5838:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5839:          }else{
                   5840:            if(first==1)
1.265     brouard  5841:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5842:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5843:          }
                   5844:          if( iage <= iagemax){
                   5845:            if(pos>=1.e-5){
1.335     brouard  5846:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5847:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5848:               }else if( nj==2){
                   5849:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5850:               }
                   5851:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5852:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5853:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5854:            } else{
1.335     brouard  5855:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5856:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5857:            }
1.240     brouard  5858:          }
1.265     brouard  5859:          pospropt[s1] +=posprop[s1];
                   5860:        } /* end loop s1 */
1.251     brouard  5861:        /* pospropt=0.; */
1.265     brouard  5862:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5863:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5864:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5865:              if(first==1){
1.265     brouard  5866:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5867:              }
1.265     brouard  5868:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5869:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5870:            }
1.265     brouard  5871:            if(s1!=0 && m!=0)
                   5872:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5873:          }
1.265     brouard  5874:        } /* end loop s1 */
1.251     brouard  5875:        posproptt=0.; 
1.265     brouard  5876:        for(s1=1; s1 <=nlstate; s1++){
                   5877:          posproptt += pospropt[s1];
1.251     brouard  5878:        }
                   5879:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5880:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5881:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5882:          if(iage <= iagemax)
                   5883:            fprintf(ficresp,"\n");
1.240     brouard  5884:        }
1.251     brouard  5885:        if(first==1)
                   5886:          printf("Others in log...\n");
                   5887:        fprintf(ficlog,"\n");
                   5888:       } /* end loop age iage */
1.265     brouard  5889:       
1.251     brouard  5890:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5891:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5892:        if(posproptt < 1.e-5){
1.265     brouard  5893:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5894:        }else{
1.265     brouard  5895:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5896:        }
1.226     brouard  5897:       }
1.251     brouard  5898:       fprintf(ficresphtm,"</tr>\n");
                   5899:       fprintf(ficresphtm,"</table>\n");
                   5900:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5901:       if(posproptt < 1.e-5){
1.251     brouard  5902:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5903:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5904:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5905:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5906:        invalidvarcomb[j1]=1;
1.226     brouard  5907:       }else{
1.338     brouard  5908:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5909:        invalidvarcomb[j1]=0;
1.226     brouard  5910:       }
1.251     brouard  5911:       fprintf(ficresphtmfr,"</table>\n");
                   5912:       fprintf(ficlog,"\n");
                   5913:       if(j!=0){
                   5914:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5915:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5916:          for(k=1; k <=(nlstate+ndeath); k++){
                   5917:            if (k != i) {
1.265     brouard  5918:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5919:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5920:                  if(j1==1){ /* All dummy covariates to zero */
                   5921:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5922:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5923:                    printf("%d%d ",i,k);
                   5924:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5925:                    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]));
                   5926:                    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]));
                   5927:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5928:                  }
1.253     brouard  5929:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5930:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5931:                    x[iage]= (double)iage;
                   5932:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5933:                    /* 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  5934:                  }
1.268     brouard  5935:                  /* Some are not finite, but linreg will ignore these ages */
                   5936:                  no=0;
1.253     brouard  5937:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5938:                  pstart[s1]=b;
                   5939:                  pstart[s1-1]=a;
1.252     brouard  5940:                }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 */ 
                   5941:                  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]);
                   5942:                  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  5943:                  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  5944:                  printf("%d%d ",i,k);
                   5945:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5946:                  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  5947:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5948:                  ;
                   5949:                }
                   5950:                /* printf("%12.7f )", param[i][jj][k]); */
                   5951:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5952:                s1++; 
1.251     brouard  5953:              } /* end jj */
                   5954:            } /* end k!= i */
                   5955:          } /* end k */
1.265     brouard  5956:        } /* end i, s1 */
1.251     brouard  5957:       } /* end j !=0 */
                   5958:     } /* end selected combination of covariate j1 */
                   5959:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5960:       printf("#Freqsummary: Starting values for the constants:\n");
                   5961:       fprintf(ficlog,"\n");
1.265     brouard  5962:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5963:        for(k=1; k <=(nlstate+ndeath); k++){
                   5964:          if (k != i) {
                   5965:            printf("%d%d ",i,k);
                   5966:            fprintf(ficlog,"%d%d ",i,k);
                   5967:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5968:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5969:              if(jj==1){ /* Age has to be done */
1.265     brouard  5970:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5971:                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]));
                   5972:                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  5973:              }
                   5974:              /* printf("%12.7f )", param[i][jj][k]); */
                   5975:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5976:              s1++; 
1.250     brouard  5977:            }
1.251     brouard  5978:            printf("\n");
                   5979:            fprintf(ficlog,"\n");
1.250     brouard  5980:          }
                   5981:        }
1.284     brouard  5982:       } /* end of state i */
1.251     brouard  5983:       printf("#Freqsummary\n");
                   5984:       fprintf(ficlog,"\n");
1.265     brouard  5985:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5986:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5987:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5988:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5989:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5990:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5991:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5992:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5993:          /* } */
                   5994:        }
1.265     brouard  5995:       } /* end loop s1 */
1.251     brouard  5996:       
                   5997:       printf("\n");
                   5998:       fprintf(ficlog,"\n");
                   5999:     } /* end j=0 */
1.249     brouard  6000:   } /* end j */
1.252     brouard  6001: 
1.253     brouard  6002:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6003:     for(i=1, jk=1; i <=nlstate; i++){
                   6004:       for(j=1; j <=nlstate+ndeath; j++){
                   6005:        if(j!=i){
                   6006:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6007:          printf("%1d%1d",i,j);
                   6008:          fprintf(ficparo,"%1d%1d",i,j);
                   6009:          for(k=1; k<=ncovmodel;k++){
                   6010:            /*    printf(" %lf",param[i][j][k]); */
                   6011:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6012:            p[jk]=pstart[jk];
                   6013:            printf(" %f ",pstart[jk]);
                   6014:            fprintf(ficparo," %f ",pstart[jk]);
                   6015:            jk++;
                   6016:          }
                   6017:          printf("\n");
                   6018:          fprintf(ficparo,"\n");
                   6019:        }
                   6020:       }
                   6021:     }
                   6022:   } /* end mle=-2 */
1.226     brouard  6023:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6024:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6025:   
1.226     brouard  6026:   fclose(ficresp);
                   6027:   fclose(ficresphtm);
                   6028:   fclose(ficresphtmfr);
1.283     brouard  6029:   free_vector(idq,1,nqfveff);
1.226     brouard  6030:   free_vector(meanq,1,nqfveff);
1.284     brouard  6031:   free_vector(stdq,1,nqfveff);
1.226     brouard  6032:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6033:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6034:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6035:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6036:   free_vector(pospropt,1,nlstate);
                   6037:   free_vector(posprop,1,nlstate);
1.251     brouard  6038:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6039:   free_vector(pp,1,nlstate);
                   6040:   /* End of freqsummary */
                   6041: }
1.126     brouard  6042: 
1.268     brouard  6043: /* Simple linear regression */
                   6044: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6045: 
                   6046:   /* y=a+bx regression */
                   6047:   double   sumx = 0.0;                        /* sum of x                      */
                   6048:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6049:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6050:   double   sumy = 0.0;                        /* sum of y                      */
                   6051:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6052:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6053:   double yhat;
                   6054:   
                   6055:   double denom=0;
                   6056:   int i;
                   6057:   int ne=*no;
                   6058:   
                   6059:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6060:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6061:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6062:       continue;
                   6063:     }
                   6064:     ne=ne+1;
                   6065:     sumx  += x[i];       
                   6066:     sumx2 += x[i]*x[i];  
                   6067:     sumxy += x[i] * y[i];
                   6068:     sumy  += y[i];      
                   6069:     sumy2 += y[i]*y[i]; 
                   6070:     denom = (ne * sumx2 - sumx*sumx);
                   6071:     /* 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); */
                   6072:   } 
                   6073:   
                   6074:   denom = (ne * sumx2 - sumx*sumx);
                   6075:   if (denom == 0) {
                   6076:     // vertical, slope m is infinity
                   6077:     *b = INFINITY;
                   6078:     *a = 0;
                   6079:     if (r) *r = 0;
                   6080:     return 1;
                   6081:   }
                   6082:   
                   6083:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6084:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6085:   if (r!=NULL) {
                   6086:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6087:       sqrt((sumx2 - sumx*sumx/ne) *
                   6088:           (sumy2 - sumy*sumy/ne));
                   6089:   }
                   6090:   *no=ne;
                   6091:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6092:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6093:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6094:       continue;
                   6095:     }
                   6096:     ne=ne+1;
                   6097:     yhat = y[i] - *a -*b* x[i];
                   6098:     sume2  += yhat * yhat ;       
                   6099:     
                   6100:     denom = (ne * sumx2 - sumx*sumx);
                   6101:     /* 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); */
                   6102:   } 
                   6103:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6104:   *sa= *sb * sqrt(sumx2/ne);
                   6105:   
                   6106:   return 0; 
                   6107: }
                   6108: 
1.126     brouard  6109: /************ Prevalence ********************/
1.227     brouard  6110: 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)
                   6111: {  
                   6112:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6113:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6114:      We still use firstpass and lastpass as another selection.
                   6115:   */
1.126     brouard  6116:  
1.227     brouard  6117:   int i, m, jk, j1, bool, z1,j, iv;
                   6118:   int mi; /* Effective wave */
                   6119:   int iage;
                   6120:   double agebegin, ageend;
                   6121: 
                   6122:   double **prop;
                   6123:   double posprop; 
                   6124:   double  y2; /* in fractional years */
                   6125:   int iagemin, iagemax;
                   6126:   int first; /** to stop verbosity which is redirected to log file */
                   6127: 
                   6128:   iagemin= (int) agemin;
                   6129:   iagemax= (int) agemax;
                   6130:   /*pp=vector(1,nlstate);*/
1.251     brouard  6131:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6132:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6133:   j1=0;
1.222     brouard  6134:   
1.227     brouard  6135:   /*j=cptcoveff;*/
                   6136:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6137:   
1.288     brouard  6138:   first=0;
1.335     brouard  6139:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6140:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6141:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6142:        prop[i][iage]=0.0;
                   6143:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6144:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6145:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6146:     
                   6147:     for (i=1; i<=imx; i++) { /* Each individual */
                   6148:       bool=1;
                   6149:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6150:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6151:        m=mw[mi][i];
                   6152:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6153:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6154:        for (z1=1; z1<=cptcoveff; z1++){
                   6155:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6156:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6157:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6158:              bool=0;
                   6159:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6160:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6161:              bool=0;
                   6162:            }
                   6163:        }
                   6164:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6165:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6166:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6167:          if(m >=firstpass && m <=lastpass){
                   6168:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6169:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6170:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6171:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6172:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6173:                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); 
                   6174:                exit(1);
                   6175:              }
                   6176:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6177:                /*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]]);*/
                   6178:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6179:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6180:              } /* end valid statuses */ 
                   6181:            } /* end selection of dates */
                   6182:          } /* end selection of waves */
                   6183:        } /* end bool */
                   6184:       } /* end wave */
                   6185:     } /* end individual */
                   6186:     for(i=iagemin; i <= iagemax+3; i++){  
                   6187:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6188:        posprop += prop[jk][i]; 
                   6189:       } 
                   6190:       
                   6191:       for(jk=1; jk <=nlstate ; jk++){      
                   6192:        if( i <=  iagemax){ 
                   6193:          if(posprop>=1.e-5){ 
                   6194:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6195:          } else{
1.288     brouard  6196:            if(!first){
                   6197:              first=1;
1.266     brouard  6198:              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]);
                   6199:            }else{
1.288     brouard  6200:              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  6201:            }
                   6202:          }
                   6203:        } 
                   6204:       }/* end jk */ 
                   6205:     }/* end i */ 
1.222     brouard  6206:      /*} *//* end i1 */
1.227     brouard  6207:   } /* end j1 */
1.222     brouard  6208:   
1.227     brouard  6209:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6210:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6211:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6212: }  /* End of prevalence */
1.126     brouard  6213: 
                   6214: /************* Waves Concatenation ***************/
                   6215: 
                   6216: 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)
                   6217: {
1.298     brouard  6218:   /* 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  6219:      Death is a valid wave (if date is known).
                   6220:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6221:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6222:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6223:   */
1.126     brouard  6224: 
1.224     brouard  6225:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6226:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6227:      double sum=0., jmean=0.;*/
1.224     brouard  6228:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6229:   int j, k=0,jk, ju, jl;
                   6230:   double sum=0.;
                   6231:   first=0;
1.214     brouard  6232:   firstwo=0;
1.217     brouard  6233:   firsthree=0;
1.218     brouard  6234:   firstfour=0;
1.164     brouard  6235:   jmin=100000;
1.126     brouard  6236:   jmax=-1;
                   6237:   jmean=0.;
1.224     brouard  6238: 
                   6239: /* Treating live states */
1.214     brouard  6240:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6241:     mi=0;  /* First valid wave */
1.227     brouard  6242:     mli=0; /* Last valid wave */
1.309     brouard  6243:     m=firstpass;  /* Loop on waves */
                   6244:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6245:       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 */
                   6246:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6247:       }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  6248:        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  6249:        mli=m;
1.224     brouard  6250:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6251:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6252:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6253:       }
1.309     brouard  6254:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6255: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6256:        break;
1.224     brouard  6257: #else
1.317     brouard  6258:        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  6259:          if(firsthree == 0){
1.302     brouard  6260:            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  6261:            firsthree=1;
1.317     brouard  6262:          }else if(firsthree >=1 && firsthree < 10){
                   6263:            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);
                   6264:            firsthree++;
                   6265:          }else if(firsthree == 10){
                   6266:            printf("Information, too many Information flags: no more reported to log either\n");
                   6267:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6268:            firsthree++;
                   6269:          }else{
                   6270:            firsthree++;
1.227     brouard  6271:          }
1.309     brouard  6272:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6273:          mli=m;
                   6274:        }
                   6275:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6276:          nbwarn++;
1.309     brouard  6277:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6278:            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);
                   6279:            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);
                   6280:          }
                   6281:          break;
                   6282:        }
                   6283:        break;
1.224     brouard  6284: #endif
1.227     brouard  6285:       }/* End m >= lastpass */
1.126     brouard  6286:     }/* end while */
1.224     brouard  6287: 
1.227     brouard  6288:     /* 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  6289:     /* After last pass */
1.224     brouard  6290: /* Treating death states */
1.214     brouard  6291:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6292:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6293:       /* } */
1.126     brouard  6294:       mi++;    /* Death is another wave */
                   6295:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6296:       /* Only death is a correct wave */
1.126     brouard  6297:       mw[mi][i]=m;
1.257     brouard  6298:     } /* else not in a death state */
1.224     brouard  6299: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6300:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6301:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6302:        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  6303:          nbwarn++;
                   6304:          if(firstfiv==0){
1.309     brouard  6305:            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  6306:            firstfiv=1;
                   6307:          }else{
1.309     brouard  6308:            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  6309:          }
1.309     brouard  6310:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6311:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6312:          nberr++;
                   6313:          if(firstwo==0){
1.309     brouard  6314:            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  6315:            firstwo=1;
                   6316:          }
1.309     brouard  6317:          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  6318:        }
1.257     brouard  6319:       }else{ /* if date of interview is unknown */
1.227     brouard  6320:        /* death is known but not confirmed by death status at any wave */
                   6321:        if(firstfour==0){
1.309     brouard  6322:          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  6323:          firstfour=1;
                   6324:        }
1.309     brouard  6325:        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  6326:       }
1.224     brouard  6327:     } /* end if date of death is known */
                   6328: #endif
1.309     brouard  6329:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6330:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6331:     if(mi==0){
                   6332:       nbwarn++;
                   6333:       if(first==0){
1.227     brouard  6334:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6335:        first=1;
1.126     brouard  6336:       }
                   6337:       if(first==1){
1.227     brouard  6338:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6339:       }
                   6340:     } /* end mi==0 */
                   6341:   } /* End individuals */
1.214     brouard  6342:   /* wav and mw are no more changed */
1.223     brouard  6343:        
1.317     brouard  6344:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6345:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6346: 
                   6347: 
1.126     brouard  6348:   for(i=1; i<=imx; i++){
                   6349:     for(mi=1; mi<wav[i];mi++){
                   6350:       if (stepm <=0)
1.227     brouard  6351:        dh[mi][i]=1;
1.126     brouard  6352:       else{
1.260     brouard  6353:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6354:          if (agedc[i] < 2*AGESUP) {
                   6355:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6356:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6357:            else if(j<0){
                   6358:              nberr++;
                   6359:              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]);
                   6360:              j=1; /* Temporary Dangerous patch */
                   6361:              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);
                   6362:              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]);
                   6363:              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);
                   6364:            }
                   6365:            k=k+1;
                   6366:            if (j >= jmax){
                   6367:              jmax=j;
                   6368:              ijmax=i;
                   6369:            }
                   6370:            if (j <= jmin){
                   6371:              jmin=j;
                   6372:              ijmin=i;
                   6373:            }
                   6374:            sum=sum+j;
                   6375:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6376:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6377:          }
                   6378:        }
                   6379:        else{
                   6380:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6381: /*       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  6382:                                        
1.227     brouard  6383:          k=k+1;
                   6384:          if (j >= jmax) {
                   6385:            jmax=j;
                   6386:            ijmax=i;
                   6387:          }
                   6388:          else if (j <= jmin){
                   6389:            jmin=j;
                   6390:            ijmin=i;
                   6391:          }
                   6392:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6393:          /*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]);*/
                   6394:          if(j<0){
                   6395:            nberr++;
                   6396:            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]);
                   6397:            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]);
                   6398:          }
                   6399:          sum=sum+j;
                   6400:        }
                   6401:        jk= j/stepm;
                   6402:        jl= j -jk*stepm;
                   6403:        ju= j -(jk+1)*stepm;
                   6404:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6405:          if(jl==0){
                   6406:            dh[mi][i]=jk;
                   6407:            bh[mi][i]=0;
                   6408:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6409:                  * to avoid the price of an extra matrix product in likelihood */
                   6410:            dh[mi][i]=jk+1;
                   6411:            bh[mi][i]=ju;
                   6412:          }
                   6413:        }else{
                   6414:          if(jl <= -ju){
                   6415:            dh[mi][i]=jk;
                   6416:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6417:                                 * is higher than the multiple of stepm and negative otherwise.
                   6418:                                 */
                   6419:          }
                   6420:          else{
                   6421:            dh[mi][i]=jk+1;
                   6422:            bh[mi][i]=ju;
                   6423:          }
                   6424:          if(dh[mi][i]==0){
                   6425:            dh[mi][i]=1; /* At least one step */
                   6426:            bh[mi][i]=ju; /* At least one step */
                   6427:            /*  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);*/
                   6428:          }
                   6429:        } /* end if mle */
1.126     brouard  6430:       }
                   6431:     } /* end wave */
                   6432:   }
                   6433:   jmean=sum/k;
                   6434:   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  6435:   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  6436: }
1.126     brouard  6437: 
                   6438: /*********** Tricode ****************************/
1.220     brouard  6439:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6440:  {
                   6441:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6442:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6443:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6444:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6445:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6446:     */
1.130     brouard  6447: 
1.242     brouard  6448:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6449:    int modmaxcovj=0; /* Modality max of covariates j */
                   6450:    int cptcode=0; /* Modality max of covariates j */
                   6451:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6452: 
                   6453: 
1.242     brouard  6454:    /* cptcoveff=0;  */
                   6455:    /* *cptcov=0; */
1.126     brouard  6456:  
1.242     brouard  6457:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6458:    for (k=1; k <= maxncov; k++)
                   6459:      for(j=1; j<=2; j++)
                   6460:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6461: 
1.242     brouard  6462:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6463:    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  6464:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6465:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6466:      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  6467:        switch(Fixed[k]) {
                   6468:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6469:         modmaxcovj=0;
                   6470:         modmincovj=0;
1.242     brouard  6471:         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  6472:           /* 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  6473:           ij=(int)(covar[Tvar[k]][i]);
                   6474:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6475:            * If product of Vn*Vm, still boolean *:
                   6476:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6477:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6478:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6479:              modality of the nth covariate of individual i. */
                   6480:           if (ij > modmaxcovj)
                   6481:             modmaxcovj=ij; 
                   6482:           else if (ij < modmincovj) 
                   6483:             modmincovj=ij; 
1.287     brouard  6484:           if (ij <0 || ij >1 ){
1.311     brouard  6485:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6486:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6487:             fflush(ficlog);
                   6488:             exit(1);
1.287     brouard  6489:           }
                   6490:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6491:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6492:             exit(1);
                   6493:           }else
                   6494:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6495:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6496:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6497:           /* getting the maximum value of the modality of the covariate
                   6498:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6499:              female ies 1, then modmaxcovj=1.
                   6500:           */
                   6501:         } /* end for loop on individuals i */
                   6502:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6503:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6504:         cptcode=modmaxcovj;
                   6505:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6506:         /*for (i=0; i<=cptcode; i++) {*/
                   6507:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6508:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6509:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6510:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6511:             if( j != -1){
                   6512:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6513:                                  covariate for which somebody answered excluding 
                   6514:                                  undefined. Usually 2: 0 and 1. */
                   6515:             }
                   6516:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6517:                                     covariate for which somebody answered including 
                   6518:                                     undefined. Usually 3: -1, 0 and 1. */
                   6519:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6520:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6521:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6522:                        
1.242     brouard  6523:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6524:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6525:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6526:         /* modmincovj=3; modmaxcovj = 7; */
                   6527:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6528:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6529:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6530:         /* nbcode[Tvar[j]][ij]=k; */
                   6531:         /* nbcode[Tvar[j]][1]=0; */
                   6532:         /* nbcode[Tvar[j]][2]=1; */
                   6533:         /* nbcode[Tvar[j]][3]=2; */
                   6534:         /* To be continued (not working yet). */
                   6535:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6536: 
                   6537:         /* 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*/
                   6538:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6539:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6540:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6541:         /*, could be restored in the future */
                   6542:         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  6543:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6544:             break;
                   6545:           }
                   6546:           ij++;
1.287     brouard  6547:           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  6548:           cptcode = ij; /* New max modality for covar j */
                   6549:         } /* end of loop on modality i=-1 to 1 or more */
                   6550:         break;
                   6551:        case 1: /* Testing on varying covariate, could be simple and
                   6552:                * should look at waves or product of fixed *
                   6553:                * varying. No time to test -1, assuming 0 and 1 only */
                   6554:         ij=0;
                   6555:         for(i=0; i<=1;i++){
                   6556:           nbcode[Tvar[k]][++ij]=i;
                   6557:         }
                   6558:         break;
                   6559:        default:
                   6560:         break;
                   6561:        } /* end switch */
                   6562:      } /* end dummy test */
1.349     brouard  6563:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6564:        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  6565:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6566:           printf("Error k=%d \n",k);
                   6567:           exit(1);
                   6568:         }
1.311     brouard  6569:         if(isnan(covar[Tvar[k]][i])){
                   6570:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6571:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6572:           fflush(ficlog);
                   6573:           exit(1);
                   6574:          }
                   6575:        }
1.335     brouard  6576:      } /* end Quanti */
1.287     brouard  6577:    } /* 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  6578:   
                   6579:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6580:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6581:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6582:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6583:      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 */ 
                   6584:      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 */
                   6585:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6586:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6587:   
                   6588:    ij=0;
                   6589:    /* 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  6590:    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 */
                   6591:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6592:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6593:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6594:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6595:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6596:        /* 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  6597:        /* If product not in single variable we don't print results */
                   6598:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6599:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6600:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6601:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6602:        /* ij            1    2                                            3  */  
                   6603:        /* Tvaraff[ij]=  4    3                                            1  */
                   6604:        /* Tmodelind[ij]=2    3                                            9  */
                   6605:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6606:        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*/
                   6607:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6608:        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 */
                   6609:        if(Fixed[k]!=0)
                   6610:         anyvaryingduminmodel=1;
                   6611:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6612:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6613:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6614:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6615:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6616:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6617:      } 
                   6618:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6619:    /* ij--; */
                   6620:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6621:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6622:                * because they can be excluded from the model and real
                   6623:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6624:    for(j=ij+1; j<= cptcovt; j++){
                   6625:      Tvaraff[j]=0;
                   6626:      Tmodelind[j]=0;
                   6627:    }
                   6628:    for(j=ntveff+1; j<= cptcovt; j++){
                   6629:      TmodelInvind[j]=0;
                   6630:    }
                   6631:    /* To be sorted */
                   6632:    ;
                   6633:  }
1.126     brouard  6634: 
1.145     brouard  6635: 
1.126     brouard  6636: /*********** Health Expectancies ****************/
                   6637: 
1.235     brouard  6638:  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  6639: 
                   6640: {
                   6641:   /* Health expectancies, no variances */
1.329     brouard  6642:   /* cij is the combination in the list of combination of dummy covariates */
                   6643:   /* strstart is a string of time at start of computing */
1.164     brouard  6644:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6645:   int nhstepma, nstepma; /* Decreasing with age */
                   6646:   double age, agelim, hf;
                   6647:   double ***p3mat;
                   6648:   double eip;
                   6649: 
1.238     brouard  6650:   /* pstamp(ficreseij); */
1.126     brouard  6651:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6652:   fprintf(ficreseij,"# Age");
                   6653:   for(i=1; i<=nlstate;i++){
                   6654:     for(j=1; j<=nlstate;j++){
                   6655:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6656:     }
                   6657:     fprintf(ficreseij," e%1d. ",i);
                   6658:   }
                   6659:   fprintf(ficreseij,"\n");
                   6660: 
                   6661:   
                   6662:   if(estepm < stepm){
                   6663:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6664:   }
                   6665:   else  hstepm=estepm;   
                   6666:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6667:    * This is mainly to measure the difference between two models: for example
                   6668:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6669:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6670:    * progression in between and thus overestimating or underestimating according
                   6671:    * to the curvature of the survival function. If, for the same date, we 
                   6672:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6673:    * to compare the new estimate of Life expectancy with the same linear 
                   6674:    * hypothesis. A more precise result, taking into account a more precise
                   6675:    * curvature will be obtained if estepm is as small as stepm. */
                   6676: 
                   6677:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6678:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6679:      nhstepm is the number of hstepm from age to agelim 
                   6680:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6681:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6682:      and note for a fixed period like estepm months */
                   6683:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6684:      survival function given by stepm (the optimization length). Unfortunately it
                   6685:      means that if the survival funtion is printed only each two years of age and if
                   6686:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6687:      results. So we changed our mind and took the option of the best precision.
                   6688:   */
                   6689:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6690: 
                   6691:   agelim=AGESUP;
                   6692:   /* If stepm=6 months */
                   6693:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6694:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6695:     
                   6696: /* nhstepm age range expressed in number of stepm */
                   6697:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6698:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6699:   /* if (stepm >= YEARM) hstepm=1;*/
                   6700:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6701:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6702: 
                   6703:   for (age=bage; age<=fage; age ++){ 
                   6704:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6705:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6706:     /* if (stepm >= YEARM) hstepm=1;*/
                   6707:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6708: 
                   6709:     /* If stepm=6 months */
                   6710:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6711:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6712:     /* 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  6713:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6714:     
                   6715:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6716:     
                   6717:     printf("%d|",(int)age);fflush(stdout);
                   6718:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6719:     
                   6720:     /* Computing expectancies */
                   6721:     for(i=1; i<=nlstate;i++)
                   6722:       for(j=1; j<=nlstate;j++)
                   6723:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6724:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6725:          
                   6726:          /* 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]);*/
                   6727: 
                   6728:        }
                   6729: 
                   6730:     fprintf(ficreseij,"%3.0f",age );
                   6731:     for(i=1; i<=nlstate;i++){
                   6732:       eip=0;
                   6733:       for(j=1; j<=nlstate;j++){
                   6734:        eip +=eij[i][j][(int)age];
                   6735:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6736:       }
                   6737:       fprintf(ficreseij,"%9.4f", eip );
                   6738:     }
                   6739:     fprintf(ficreseij,"\n");
                   6740:     
                   6741:   }
                   6742:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6743:   printf("\n");
                   6744:   fprintf(ficlog,"\n");
                   6745:   
                   6746: }
                   6747: 
1.235     brouard  6748:  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  6749: 
                   6750: {
                   6751:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6752:      to initial status i, ei. .
1.126     brouard  6753:   */
1.336     brouard  6754:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6755:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6756:   int nhstepma, nstepma; /* Decreasing with age */
                   6757:   double age, agelim, hf;
                   6758:   double ***p3matp, ***p3matm, ***varhe;
                   6759:   double **dnewm,**doldm;
                   6760:   double *xp, *xm;
                   6761:   double **gp, **gm;
                   6762:   double ***gradg, ***trgradg;
                   6763:   int theta;
                   6764: 
                   6765:   double eip, vip;
                   6766: 
                   6767:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6768:   xp=vector(1,npar);
                   6769:   xm=vector(1,npar);
                   6770:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6771:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6772:   
                   6773:   pstamp(ficresstdeij);
                   6774:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6775:   fprintf(ficresstdeij,"# Age");
                   6776:   for(i=1; i<=nlstate;i++){
                   6777:     for(j=1; j<=nlstate;j++)
                   6778:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6779:     fprintf(ficresstdeij," e%1d. ",i);
                   6780:   }
                   6781:   fprintf(ficresstdeij,"\n");
                   6782: 
                   6783:   pstamp(ficrescveij);
                   6784:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6785:   fprintf(ficrescveij,"# Age");
                   6786:   for(i=1; i<=nlstate;i++)
                   6787:     for(j=1; j<=nlstate;j++){
                   6788:       cptj= (j-1)*nlstate+i;
                   6789:       for(i2=1; i2<=nlstate;i2++)
                   6790:        for(j2=1; j2<=nlstate;j2++){
                   6791:          cptj2= (j2-1)*nlstate+i2;
                   6792:          if(cptj2 <= cptj)
                   6793:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6794:        }
                   6795:     }
                   6796:   fprintf(ficrescveij,"\n");
                   6797:   
                   6798:   if(estepm < stepm){
                   6799:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6800:   }
                   6801:   else  hstepm=estepm;   
                   6802:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6803:    * This is mainly to measure the difference between two models: for example
                   6804:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6805:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6806:    * progression in between and thus overestimating or underestimating according
                   6807:    * to the curvature of the survival function. If, for the same date, we 
                   6808:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6809:    * to compare the new estimate of Life expectancy with the same linear 
                   6810:    * hypothesis. A more precise result, taking into account a more precise
                   6811:    * curvature will be obtained if estepm is as small as stepm. */
                   6812: 
                   6813:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6814:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6815:      nhstepm is the number of hstepm from age to agelim 
                   6816:      nstepm is the number of stepm from age to agelin. 
                   6817:      Look at hpijx to understand the reason of that which relies in memory size
                   6818:      and note for a fixed period like estepm months */
                   6819:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6820:      survival function given by stepm (the optimization length). Unfortunately it
                   6821:      means that if the survival funtion is printed only each two years of age and if
                   6822:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6823:      results. So we changed our mind and took the option of the best precision.
                   6824:   */
                   6825:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6826: 
                   6827:   /* If stepm=6 months */
                   6828:   /* nhstepm age range expressed in number of stepm */
                   6829:   agelim=AGESUP;
                   6830:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6831:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6832:   /* if (stepm >= YEARM) hstepm=1;*/
                   6833:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6834:   
                   6835:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6836:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6837:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6838:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6839:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6840:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6841: 
                   6842:   for (age=bage; age<=fage; age ++){ 
                   6843:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6844:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6845:     /* if (stepm >= YEARM) hstepm=1;*/
                   6846:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6847:                
1.126     brouard  6848:     /* If stepm=6 months */
                   6849:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6850:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6851:     
                   6852:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6853:                
1.126     brouard  6854:     /* Computing  Variances of health expectancies */
                   6855:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6856:        decrease memory allocation */
                   6857:     for(theta=1; theta <=npar; theta++){
                   6858:       for(i=1; i<=npar; i++){ 
1.222     brouard  6859:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6860:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6861:       }
1.235     brouard  6862:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6863:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6864:                        
1.126     brouard  6865:       for(j=1; j<= nlstate; j++){
1.222     brouard  6866:        for(i=1; i<=nlstate; i++){
                   6867:          for(h=0; h<=nhstepm-1; h++){
                   6868:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6869:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6870:          }
                   6871:        }
1.126     brouard  6872:       }
1.218     brouard  6873:                        
1.126     brouard  6874:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6875:        for(h=0; h<=nhstepm-1; h++){
                   6876:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6877:        }
1.126     brouard  6878:     }/* End theta */
                   6879:     
                   6880:     
                   6881:     for(h=0; h<=nhstepm-1; h++)
                   6882:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6883:        for(theta=1; theta <=npar; theta++)
                   6884:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6885:     
1.218     brouard  6886:                
1.222     brouard  6887:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6888:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6889:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6890:                
1.222     brouard  6891:     printf("%d|",(int)age);fflush(stdout);
                   6892:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6893:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6894:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6895:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6896:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6897:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6898:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6899:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6900:       }
                   6901:     }
1.320     brouard  6902:     /* if((int)age ==50){ */
                   6903:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6904:     /* } */
1.126     brouard  6905:     /* Computing expectancies */
1.235     brouard  6906:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6907:     for(i=1; i<=nlstate;i++)
                   6908:       for(j=1; j<=nlstate;j++)
1.222     brouard  6909:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6910:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6911:                                        
1.222     brouard  6912:          /* 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  6913:                                        
1.222     brouard  6914:        }
1.269     brouard  6915: 
                   6916:     /* Standard deviation of expectancies ij */                
1.126     brouard  6917:     fprintf(ficresstdeij,"%3.0f",age );
                   6918:     for(i=1; i<=nlstate;i++){
                   6919:       eip=0.;
                   6920:       vip=0.;
                   6921:       for(j=1; j<=nlstate;j++){
1.222     brouard  6922:        eip += eij[i][j][(int)age];
                   6923:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6924:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6925:        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  6926:       }
                   6927:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6928:     }
                   6929:     fprintf(ficresstdeij,"\n");
1.218     brouard  6930:                
1.269     brouard  6931:     /* Variance of expectancies ij */          
1.126     brouard  6932:     fprintf(ficrescveij,"%3.0f",age );
                   6933:     for(i=1; i<=nlstate;i++)
                   6934:       for(j=1; j<=nlstate;j++){
1.222     brouard  6935:        cptj= (j-1)*nlstate+i;
                   6936:        for(i2=1; i2<=nlstate;i2++)
                   6937:          for(j2=1; j2<=nlstate;j2++){
                   6938:            cptj2= (j2-1)*nlstate+i2;
                   6939:            if(cptj2 <= cptj)
                   6940:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6941:          }
1.126     brouard  6942:       }
                   6943:     fprintf(ficrescveij,"\n");
1.218     brouard  6944:                
1.126     brouard  6945:   }
                   6946:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6947:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6948:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6949:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6950:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6951:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6952:   printf("\n");
                   6953:   fprintf(ficlog,"\n");
1.218     brouard  6954:        
1.126     brouard  6955:   free_vector(xm,1,npar);
                   6956:   free_vector(xp,1,npar);
                   6957:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6958:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6959:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6960: }
1.218     brouard  6961:  
1.126     brouard  6962: /************ Variance ******************/
1.235     brouard  6963:  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  6964:  {
1.279     brouard  6965:    /** Variance of health expectancies 
                   6966:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6967:     * double **newm;
                   6968:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6969:     */
1.218     brouard  6970:   
                   6971:    /* int movingaverage(); */
                   6972:    double **dnewm,**doldm;
                   6973:    double **dnewmp,**doldmp;
                   6974:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6975:    int first=0;
1.218     brouard  6976:    int k;
                   6977:    double *xp;
1.279     brouard  6978:    double **gp, **gm;  /**< for var eij */
                   6979:    double ***gradg, ***trgradg; /**< for var eij */
                   6980:    double **gradgp, **trgradgp; /**< for var p point j */
                   6981:    double *gpp, *gmp; /**< for var p point j */
                   6982:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6983:    double ***p3mat;
                   6984:    double age,agelim, hf;
                   6985:    /* double ***mobaverage; */
                   6986:    int theta;
                   6987:    char digit[4];
                   6988:    char digitp[25];
                   6989: 
                   6990:    char fileresprobmorprev[FILENAMELENGTH];
                   6991: 
                   6992:    if(popbased==1){
                   6993:      if(mobilav!=0)
                   6994:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6995:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6996:    }
                   6997:    else 
                   6998:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6999: 
1.218     brouard  7000:    /* if (mobilav!=0) { */
                   7001:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7002:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7003:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7004:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7005:    /*   } */
                   7006:    /* } */
                   7007: 
                   7008:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7009:    sprintf(digit,"%-d",ij);
                   7010:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7011:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7012:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7013:    strcat(fileresprobmorprev,fileresu);
                   7014:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7015:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7016:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7017:    }
                   7018:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7019:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7020:    pstamp(ficresprobmorprev);
                   7021:    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  7022:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7023: 
                   7024:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7025:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7026:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7027:    /* } */
                   7028:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7029:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7030:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7031:    }
1.337     brouard  7032:    /* for(j=1;j<=cptcoveff;j++)  */
                   7033:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7034:    fprintf(ficresprobmorprev,"\n");
                   7035: 
1.218     brouard  7036:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7037:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7038:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7039:      for(i=1; i<=nlstate;i++)
                   7040:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7041:    }  
                   7042:    fprintf(ficresprobmorprev,"\n");
                   7043:   
                   7044:    fprintf(ficgp,"\n# Routine varevsij");
                   7045:    fprintf(ficgp,"\nunset title \n");
                   7046:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7047:    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");
                   7048:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7049: 
1.218     brouard  7050:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7051:    pstamp(ficresvij);
                   7052:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7053:    if(popbased==1)
                   7054:      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);
                   7055:    else
                   7056:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7057:    fprintf(ficresvij,"# Age");
                   7058:    for(i=1; i<=nlstate;i++)
                   7059:      for(j=1; j<=nlstate;j++)
                   7060:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7061:    fprintf(ficresvij,"\n");
                   7062: 
                   7063:    xp=vector(1,npar);
                   7064:    dnewm=matrix(1,nlstate,1,npar);
                   7065:    doldm=matrix(1,nlstate,1,nlstate);
                   7066:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7067:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7068: 
                   7069:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7070:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7071:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7072:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7073:   
1.218     brouard  7074:    if(estepm < stepm){
                   7075:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7076:    }
                   7077:    else  hstepm=estepm;   
                   7078:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7079:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7080:       nhstepm is the number of hstepm from age to agelim 
                   7081:       nstepm is the number of stepm from age to agelim. 
                   7082:       Look at function hpijx to understand why because of memory size limitations, 
                   7083:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7084:       survival function given by stepm (the optimization length). Unfortunately it
                   7085:       means that if the survival funtion is printed every two years of age and if
                   7086:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7087:       results. So we changed our mind and took the option of the best precision.
                   7088:    */
                   7089:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7090:    agelim = AGESUP;
                   7091:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7092:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7093:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7094:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7095:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7096:      gp=matrix(0,nhstepm,1,nlstate);
                   7097:      gm=matrix(0,nhstepm,1,nlstate);
                   7098:                
                   7099:                
                   7100:      for(theta=1; theta <=npar; theta++){
                   7101:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7102:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7103:        }
1.279     brouard  7104:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7105:        * returns into prlim .
1.288     brouard  7106:        */
1.242     brouard  7107:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7108: 
                   7109:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7110:        if (popbased==1) {
                   7111:         if(mobilav ==0){
                   7112:           for(i=1; i<=nlstate;i++)
                   7113:             prlim[i][i]=probs[(int)age][i][ij];
                   7114:         }else{ /* mobilav */ 
                   7115:           for(i=1; i<=nlstate;i++)
                   7116:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7117:         }
                   7118:        }
1.295     brouard  7119:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7120:        */                      
                   7121:        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  7122:        /**< 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  7123:        * at horizon h in state j including mortality.
                   7124:        */
1.218     brouard  7125:        for(j=1; j<= nlstate; j++){
                   7126:         for(h=0; h<=nhstepm; h++){
                   7127:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7128:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7129:         }
                   7130:        }
1.279     brouard  7131:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7132:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7133:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7134:        */
                   7135:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7136:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7137:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7138:        }
                   7139:        
                   7140:        /* Again with minus shift */
1.218     brouard  7141:                        
                   7142:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7143:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7144: 
1.242     brouard  7145:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7146:                        
                   7147:        if (popbased==1) {
                   7148:         if(mobilav ==0){
                   7149:           for(i=1; i<=nlstate;i++)
                   7150:             prlim[i][i]=probs[(int)age][i][ij];
                   7151:         }else{ /* mobilav */ 
                   7152:           for(i=1; i<=nlstate;i++)
                   7153:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7154:         }
                   7155:        }
                   7156:                        
1.235     brouard  7157:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7158:                        
                   7159:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7160:         for(h=0; h<=nhstepm; h++){
                   7161:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7162:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7163:         }
                   7164:        }
                   7165:        /* This for computing probability of death (h=1 means
                   7166:          computed over hstepm matrices product = hstepm*stepm months) 
                   7167:          as a weighted average of prlim.
                   7168:        */
                   7169:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7170:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7171:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7172:        }    
1.279     brouard  7173:        /* end shifting computations */
                   7174: 
                   7175:        /**< Computing gradient matrix at horizon h 
                   7176:        */
1.218     brouard  7177:        for(j=1; j<= nlstate; j++) /* vareij */
                   7178:         for(h=0; h<=nhstepm; h++){
                   7179:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7180:         }
1.279     brouard  7181:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7182:        */
                   7183:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7184:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7185:        }
                   7186:                        
                   7187:      } /* End theta */
1.279     brouard  7188:      
                   7189:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7190:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7191:                
                   7192:      for(h=0; h<=nhstepm; h++) /* veij */
                   7193:        for(j=1; j<=nlstate;j++)
                   7194:         for(theta=1; theta <=npar; theta++)
                   7195:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7196:                
                   7197:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7198:        for(theta=1; theta <=npar; theta++)
                   7199:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7200:      /**< as well as its transposed matrix 
                   7201:       */               
1.218     brouard  7202:                
                   7203:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7204:      for(i=1;i<=nlstate;i++)
                   7205:        for(j=1;j<=nlstate;j++)
                   7206:         vareij[i][j][(int)age] =0.;
1.279     brouard  7207: 
                   7208:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7209:       * and k (nhstepm) formula 15 of article
                   7210:       * Lievre-Brouard-Heathcote
                   7211:       */
                   7212:      
1.218     brouard  7213:      for(h=0;h<=nhstepm;h++){
                   7214:        for(k=0;k<=nhstepm;k++){
                   7215:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7216:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7217:         for(i=1;i<=nlstate;i++)
                   7218:           for(j=1;j<=nlstate;j++)
                   7219:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7220:        }
                   7221:      }
                   7222:                
1.279     brouard  7223:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7224:       * p.j overall mortality formula 49 but computed directly because
                   7225:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7226:       * wix is independent of theta.
                   7227:       */
1.218     brouard  7228:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7229:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7230:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7231:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7232:         varppt[j][i]=doldmp[j][i];
                   7233:      /* end ppptj */
                   7234:      /*  x centered again */
                   7235:                
1.242     brouard  7236:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7237:                
                   7238:      if (popbased==1) {
                   7239:        if(mobilav ==0){
                   7240:         for(i=1; i<=nlstate;i++)
                   7241:           prlim[i][i]=probs[(int)age][i][ij];
                   7242:        }else{ /* mobilav */ 
                   7243:         for(i=1; i<=nlstate;i++)
                   7244:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7245:        }
                   7246:      }
                   7247:                
                   7248:      /* This for computing probability of death (h=1 means
                   7249:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7250:        as a weighted average of prlim.
                   7251:      */
1.235     brouard  7252:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7253:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7254:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7255:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7256:      }    
                   7257:      /* end probability of death */
                   7258:                
                   7259:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7260:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7261:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7262:        for(i=1; i<=nlstate;i++){
                   7263:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7264:        }
                   7265:      } 
                   7266:      fprintf(ficresprobmorprev,"\n");
                   7267:                
                   7268:      fprintf(ficresvij,"%.0f ",age );
                   7269:      for(i=1; i<=nlstate;i++)
                   7270:        for(j=1; j<=nlstate;j++){
                   7271:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7272:        }
                   7273:      fprintf(ficresvij,"\n");
                   7274:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7275:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7276:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7277:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7278:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7279:    } /* End age */
                   7280:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7281:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7282:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7283:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7284:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7285:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7286:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7287:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7288:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7289:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7290:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7291:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7292:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7293:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7294:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7295:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7296:    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);
                   7297:    /*  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  7298:     */
1.218     brouard  7299:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7300:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7301: 
1.218     brouard  7302:    free_vector(xp,1,npar);
                   7303:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7304:    free_matrix(dnewm,1,nlstate,1,npar);
                   7305:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7306:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7307:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7308:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7309:    fclose(ficresprobmorprev);
                   7310:    fflush(ficgp);
                   7311:    fflush(fichtm); 
                   7312:  }  /* end varevsij */
1.126     brouard  7313: 
                   7314: /************ Variance of prevlim ******************/
1.269     brouard  7315:  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  7316: {
1.205     brouard  7317:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7318:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7319: 
1.268     brouard  7320:   double **dnewmpar,**doldm;
1.126     brouard  7321:   int i, j, nhstepm, hstepm;
                   7322:   double *xp;
                   7323:   double *gp, *gm;
                   7324:   double **gradg, **trgradg;
1.208     brouard  7325:   double **mgm, **mgp;
1.126     brouard  7326:   double age,agelim;
                   7327:   int theta;
                   7328:   
                   7329:   pstamp(ficresvpl);
1.288     brouard  7330:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7331:   fprintf(ficresvpl,"# Age ");
                   7332:   if(nresult >=1)
                   7333:     fprintf(ficresvpl," Result# ");
1.126     brouard  7334:   for(i=1; i<=nlstate;i++)
                   7335:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7336:   fprintf(ficresvpl,"\n");
                   7337: 
                   7338:   xp=vector(1,npar);
1.268     brouard  7339:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7340:   doldm=matrix(1,nlstate,1,nlstate);
                   7341:   
                   7342:   hstepm=1*YEARM; /* Every year of age */
                   7343:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7344:   agelim = AGESUP;
                   7345:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7346:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7347:     if (stepm >= YEARM) hstepm=1;
                   7348:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7349:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7350:     mgp=matrix(1,npar,1,nlstate);
                   7351:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7352:     gp=vector(1,nlstate);
                   7353:     gm=vector(1,nlstate);
                   7354: 
                   7355:     for(theta=1; theta <=npar; theta++){
                   7356:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7357:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7358:       }
1.288     brouard  7359:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7360:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7361:       /* else */
                   7362:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7363:       for(i=1;i<=nlstate;i++){
1.126     brouard  7364:        gp[i] = prlim[i][i];
1.208     brouard  7365:        mgp[theta][i] = prlim[i][i];
                   7366:       }
1.126     brouard  7367:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7368:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7369:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7370:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7371:       /* else */
                   7372:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7373:       for(i=1;i<=nlstate;i++){
1.126     brouard  7374:        gm[i] = prlim[i][i];
1.208     brouard  7375:        mgm[theta][i] = prlim[i][i];
                   7376:       }
1.126     brouard  7377:       for(i=1;i<=nlstate;i++)
                   7378:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7379:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7380:     } /* End theta */
                   7381: 
                   7382:     trgradg =matrix(1,nlstate,1,npar);
                   7383: 
                   7384:     for(j=1; j<=nlstate;j++)
                   7385:       for(theta=1; theta <=npar; theta++)
                   7386:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7387:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7388:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7389:     /*   for(j=1; j<=nlstate;j++){ */
                   7390:     /*         printf(" %d ",j); */
                   7391:     /*         for(theta=1; theta <=npar; theta++) */
                   7392:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7393:     /*         printf("\n "); */
                   7394:     /*   } */
                   7395:     /* } */
                   7396:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7397:     /*   printf("\n gradg %d ",(int)age); */
                   7398:     /*   for(j=1; j<=nlstate;j++){ */
                   7399:     /*         printf("%d ",j); */
                   7400:     /*         for(theta=1; theta <=npar; theta++) */
                   7401:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7402:     /*         printf("\n "); */
                   7403:     /*   } */
                   7404:     /* } */
1.126     brouard  7405: 
                   7406:     for(i=1;i<=nlstate;i++)
                   7407:       varpl[i][(int)age] =0.;
1.209     brouard  7408:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7409:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7410:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7411:     }else{
1.268     brouard  7412:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7413:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7414:     }
1.126     brouard  7415:     for(i=1;i<=nlstate;i++)
                   7416:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7417: 
                   7418:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7419:     if(nresult >=1)
                   7420:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7421:     for(i=1; i<=nlstate;i++){
1.126     brouard  7422:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7423:       /* for(j=1;j<=nlstate;j++) */
                   7424:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7425:     }
1.126     brouard  7426:     fprintf(ficresvpl,"\n");
                   7427:     free_vector(gp,1,nlstate);
                   7428:     free_vector(gm,1,nlstate);
1.208     brouard  7429:     free_matrix(mgm,1,npar,1,nlstate);
                   7430:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7431:     free_matrix(gradg,1,npar,1,nlstate);
                   7432:     free_matrix(trgradg,1,nlstate,1,npar);
                   7433:   } /* End age */
                   7434: 
                   7435:   free_vector(xp,1,npar);
                   7436:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7437:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7438: 
                   7439: }
                   7440: 
                   7441: 
                   7442: /************ Variance of backprevalence limit ******************/
1.269     brouard  7443:  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  7444: {
                   7445:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7446:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7447: 
                   7448:   double **dnewmpar,**doldm;
                   7449:   int i, j, nhstepm, hstepm;
                   7450:   double *xp;
                   7451:   double *gp, *gm;
                   7452:   double **gradg, **trgradg;
                   7453:   double **mgm, **mgp;
                   7454:   double age,agelim;
                   7455:   int theta;
                   7456:   
                   7457:   pstamp(ficresvbl);
                   7458:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7459:   fprintf(ficresvbl,"# Age ");
                   7460:   if(nresult >=1)
                   7461:     fprintf(ficresvbl," Result# ");
                   7462:   for(i=1; i<=nlstate;i++)
                   7463:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7464:   fprintf(ficresvbl,"\n");
                   7465: 
                   7466:   xp=vector(1,npar);
                   7467:   dnewmpar=matrix(1,nlstate,1,npar);
                   7468:   doldm=matrix(1,nlstate,1,nlstate);
                   7469:   
                   7470:   hstepm=1*YEARM; /* Every year of age */
                   7471:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7472:   agelim = AGEINF;
                   7473:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7474:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7475:     if (stepm >= YEARM) hstepm=1;
                   7476:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7477:     gradg=matrix(1,npar,1,nlstate);
                   7478:     mgp=matrix(1,npar,1,nlstate);
                   7479:     mgm=matrix(1,npar,1,nlstate);
                   7480:     gp=vector(1,nlstate);
                   7481:     gm=vector(1,nlstate);
                   7482: 
                   7483:     for(theta=1; theta <=npar; theta++){
                   7484:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7485:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7486:       }
                   7487:       if(mobilavproj > 0 )
                   7488:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7489:       else
                   7490:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7491:       for(i=1;i<=nlstate;i++){
                   7492:        gp[i] = bprlim[i][i];
                   7493:        mgp[theta][i] = bprlim[i][i];
                   7494:       }
                   7495:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7496:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7497:        if(mobilavproj > 0 )
                   7498:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7499:        else
                   7500:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7501:       for(i=1;i<=nlstate;i++){
                   7502:        gm[i] = bprlim[i][i];
                   7503:        mgm[theta][i] = bprlim[i][i];
                   7504:       }
                   7505:       for(i=1;i<=nlstate;i++)
                   7506:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7507:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7508:     } /* End theta */
                   7509: 
                   7510:     trgradg =matrix(1,nlstate,1,npar);
                   7511: 
                   7512:     for(j=1; j<=nlstate;j++)
                   7513:       for(theta=1; theta <=npar; theta++)
                   7514:        trgradg[j][theta]=gradg[theta][j];
                   7515:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7516:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7517:     /*   for(j=1; j<=nlstate;j++){ */
                   7518:     /*         printf(" %d ",j); */
                   7519:     /*         for(theta=1; theta <=npar; theta++) */
                   7520:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7521:     /*         printf("\n "); */
                   7522:     /*   } */
                   7523:     /* } */
                   7524:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7525:     /*   printf("\n gradg %d ",(int)age); */
                   7526:     /*   for(j=1; j<=nlstate;j++){ */
                   7527:     /*         printf("%d ",j); */
                   7528:     /*         for(theta=1; theta <=npar; theta++) */
                   7529:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7530:     /*         printf("\n "); */
                   7531:     /*   } */
                   7532:     /* } */
                   7533: 
                   7534:     for(i=1;i<=nlstate;i++)
                   7535:       varbpl[i][(int)age] =0.;
                   7536:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7537:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7538:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7539:     }else{
                   7540:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7541:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7542:     }
                   7543:     for(i=1;i<=nlstate;i++)
                   7544:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7545: 
                   7546:     fprintf(ficresvbl,"%.0f ",age );
                   7547:     if(nresult >=1)
                   7548:       fprintf(ficresvbl,"%d ",nres );
                   7549:     for(i=1; i<=nlstate;i++)
                   7550:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7551:     fprintf(ficresvbl,"\n");
                   7552:     free_vector(gp,1,nlstate);
                   7553:     free_vector(gm,1,nlstate);
                   7554:     free_matrix(mgm,1,npar,1,nlstate);
                   7555:     free_matrix(mgp,1,npar,1,nlstate);
                   7556:     free_matrix(gradg,1,npar,1,nlstate);
                   7557:     free_matrix(trgradg,1,nlstate,1,npar);
                   7558:   } /* End age */
                   7559: 
                   7560:   free_vector(xp,1,npar);
                   7561:   free_matrix(doldm,1,nlstate,1,npar);
                   7562:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7563: 
                   7564: }
                   7565: 
                   7566: /************ Variance of one-step probabilities  ******************/
                   7567: 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  7568:  {
                   7569:    int i, j=0,  k1, l1, tj;
                   7570:    int k2, l2, j1,  z1;
                   7571:    int k=0, l;
                   7572:    int first=1, first1, first2;
1.326     brouard  7573:    int nres=0; /* New */
1.222     brouard  7574:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7575:    double **dnewm,**doldm;
                   7576:    double *xp;
                   7577:    double *gp, *gm;
                   7578:    double **gradg, **trgradg;
                   7579:    double **mu;
                   7580:    double age, cov[NCOVMAX+1];
                   7581:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7582:    int theta;
                   7583:    char fileresprob[FILENAMELENGTH];
                   7584:    char fileresprobcov[FILENAMELENGTH];
                   7585:    char fileresprobcor[FILENAMELENGTH];
                   7586:    double ***varpij;
                   7587: 
                   7588:    strcpy(fileresprob,"PROB_"); 
                   7589:    strcat(fileresprob,fileres);
                   7590:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7591:      printf("Problem with resultfile: %s\n", fileresprob);
                   7592:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7593:    }
                   7594:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7595:    strcat(fileresprobcov,fileresu);
                   7596:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7597:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7598:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7599:    }
                   7600:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7601:    strcat(fileresprobcor,fileresu);
                   7602:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7603:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7604:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7605:    }
                   7606:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7607:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7608:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7609:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7610:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7611:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7612:    pstamp(ficresprob);
                   7613:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7614:    fprintf(ficresprob,"# Age");
                   7615:    pstamp(ficresprobcov);
                   7616:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7617:    fprintf(ficresprobcov,"# Age");
                   7618:    pstamp(ficresprobcor);
                   7619:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7620:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7621: 
                   7622: 
1.222     brouard  7623:    for(i=1; i<=nlstate;i++)
                   7624:      for(j=1; j<=(nlstate+ndeath);j++){
                   7625:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7626:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7627:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7628:      }  
                   7629:    /* fprintf(ficresprob,"\n");
                   7630:       fprintf(ficresprobcov,"\n");
                   7631:       fprintf(ficresprobcor,"\n");
                   7632:    */
                   7633:    xp=vector(1,npar);
                   7634:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7635:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7636:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7637:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7638:    first=1;
                   7639:    fprintf(ficgp,"\n# Routine varprob");
                   7640:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7641:    fprintf(fichtm,"\n");
                   7642: 
1.288     brouard  7643:    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  7644:    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);
                   7645:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7646: and drawn. It helps understanding how is the covariance between two incidences.\
                   7647:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7648:    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  7649: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7650: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7651: standard deviations wide on each axis. <br>\
                   7652:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7653:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7654: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7655: 
1.222     brouard  7656:    cov[1]=1;
                   7657:    /* tj=cptcoveff; */
1.225     brouard  7658:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7659:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7660:    j1=0;
1.332     brouard  7661: 
                   7662:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7663:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7664:      /* 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  7665:      if(tj != 1 && TKresult[nres]!= j1)
                   7666:        continue;
                   7667: 
                   7668:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7669:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7670:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7671:      if  (cptcovn>0) {
1.334     brouard  7672:        fprintf(ficresprob, "\n#********** Variable ");
                   7673:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7674:        fprintf(ficgp, "\n#********** Variable ");
                   7675:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7676:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7677: 
                   7678:        /* Including quantitative variables of the resultline to be done */
                   7679:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7680:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7681:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7682:         /* 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  7683:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7684:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7685:             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  */
                   7686:             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  */
                   7687:             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  */
                   7688:             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  */
                   7689:             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  */
                   7690:             fprintf(ficresprob,"fixed ");
                   7691:             fprintf(ficresprobcov,"fixed ");
                   7692:             fprintf(ficgp,"fixed ");
                   7693:             fprintf(fichtmcov,"fixed ");
                   7694:             fprintf(ficresprobcor,"fixed ");
                   7695:           }else{
                   7696:             fprintf(ficresprob,"varyi ");
                   7697:             fprintf(ficresprobcov,"varyi ");
                   7698:             fprintf(ficgp,"varyi ");
                   7699:             fprintf(fichtmcov,"varyi ");
                   7700:             fprintf(ficresprobcor,"varyi ");
                   7701:           }
                   7702:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7703:           /* For each selected (single) quantitative value */
1.337     brouard  7704:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7705:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7706:             fprintf(ficresprob,"fixed ");
                   7707:             fprintf(ficresprobcov,"fixed ");
                   7708:             fprintf(ficgp,"fixed ");
                   7709:             fprintf(fichtmcov,"fixed ");
                   7710:             fprintf(ficresprobcor,"fixed ");
                   7711:           }else{
                   7712:             fprintf(ficresprob,"varyi ");
                   7713:             fprintf(ficresprobcov,"varyi ");
                   7714:             fprintf(ficgp,"varyi ");
                   7715:             fprintf(fichtmcov,"varyi ");
                   7716:             fprintf(ficresprobcor,"varyi ");
                   7717:           }
                   7718:         }else{
                   7719:           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 */
                   7720:           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 */
                   7721:           exit(1);
                   7722:         }
                   7723:        } /* End loop on variable of this resultline */
                   7724:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7725:        fprintf(ficresprob, "**********\n#\n");
                   7726:        fprintf(ficresprobcov, "**********\n#\n");
                   7727:        fprintf(ficgp, "**********\n#\n");
                   7728:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7729:        fprintf(ficresprobcor, "**********\n#");    
                   7730:        if(invalidvarcomb[j1]){
                   7731:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7732:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7733:         continue;
                   7734:        }
                   7735:      }
                   7736:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7737:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7738:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7739:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7740:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7741:        cov[2]=age;
                   7742:        if(nagesqr==1)
                   7743:         cov[3]= age*age;
1.334     brouard  7744:        /* New code end of combination but for each resultline */
                   7745:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7746:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7747:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7748:         }else{
1.334     brouard  7749:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7750:         }
1.334     brouard  7751:        }/* End of loop on model equation */
                   7752: /* Old code */
                   7753:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7754:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7755:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7756:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7757:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7758:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7759:        /*                                                                  * 1  1 1 1 1 */
                   7760:        /*                                                                  * 2  2 1 1 1 */
                   7761:        /*                                                                  * 3  1 2 1 1 */
                   7762:        /*                                                                  *\/ */
                   7763:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7764:        /* } */
                   7765:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7766:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7767:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7768:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7769:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7770:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7771:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7772:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7773:        /*         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]); */
                   7774:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7775:        /*         /\* exit(1); *\/ */
                   7776:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7777:        /*       } */
                   7778:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7779:        /* } */
                   7780:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7781:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7782:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7783:        /*           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]])]; */
                   7784:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7785:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7786:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7787:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7788:        /*         } */
                   7789:        /*       }else{ */
                   7790:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7791:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7792:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7793:        /*         }else{ */
                   7794:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7795:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7796:        /*         } */
                   7797:        /*       } */
                   7798:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7799:        /* } */                 
1.326     brouard  7800: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7801:        for(theta=1; theta <=npar; theta++){
                   7802:         for(i=1; i<=npar; i++)
                   7803:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7804:                                
1.222     brouard  7805:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7806:                                
1.222     brouard  7807:         k=0;
                   7808:         for(i=1; i<= (nlstate); i++){
                   7809:           for(j=1; j<=(nlstate+ndeath);j++){
                   7810:             k=k+1;
                   7811:             gp[k]=pmmij[i][j];
                   7812:           }
                   7813:         }
1.220     brouard  7814:                                
1.222     brouard  7815:         for(i=1; i<=npar; i++)
                   7816:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7817:                                
1.222     brouard  7818:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7819:         k=0;
                   7820:         for(i=1; i<=(nlstate); i++){
                   7821:           for(j=1; j<=(nlstate+ndeath);j++){
                   7822:             k=k+1;
                   7823:             gm[k]=pmmij[i][j];
                   7824:           }
                   7825:         }
1.220     brouard  7826:                                
1.222     brouard  7827:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7828:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7829:        }
1.126     brouard  7830: 
1.222     brouard  7831:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7832:         for(theta=1; theta <=npar; theta++)
                   7833:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7834:                        
1.222     brouard  7835:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7836:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7837:                        
1.222     brouard  7838:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7839:                        
1.222     brouard  7840:        k=0;
                   7841:        for(i=1; i<=(nlstate); i++){
                   7842:         for(j=1; j<=(nlstate+ndeath);j++){
                   7843:           k=k+1;
                   7844:           mu[k][(int) age]=pmmij[i][j];
                   7845:         }
                   7846:        }
                   7847:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7848:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7849:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7850:                        
1.222     brouard  7851:        /*printf("\n%d ",(int)age);
                   7852:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7853:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7854:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7855:         }*/
1.220     brouard  7856:                        
1.222     brouard  7857:        fprintf(ficresprob,"\n%d ",(int)age);
                   7858:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7859:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7860:                        
1.222     brouard  7861:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7862:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7863:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7864:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7865:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7866:        }
                   7867:        i=0;
                   7868:        for (k=1; k<=(nlstate);k++){
                   7869:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7870:           i++;
                   7871:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7872:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7873:           for (j=1; j<=i;j++){
                   7874:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7875:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7876:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7877:           }
                   7878:         }
                   7879:        }/* end of loop for state */
                   7880:      } /* end of loop for age */
                   7881:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7882:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7883:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7884:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7885:     
                   7886:      /* Confidence intervalle of pij  */
                   7887:      /*
                   7888:        fprintf(ficgp,"\nunset parametric;unset label");
                   7889:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7890:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7891:        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);
                   7892:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7893:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7894:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7895:      */
                   7896:                
                   7897:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7898:      first1=1;first2=2;
                   7899:      for (k2=1; k2<=(nlstate);k2++){
                   7900:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7901:         if(l2==k2) continue;
                   7902:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7903:         for (k1=1; k1<=(nlstate);k1++){
                   7904:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7905:             if(l1==k1) continue;
                   7906:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7907:             if(i<=j) continue;
                   7908:             for (age=bage; age<=fage; age ++){ 
                   7909:               if ((int)age %5==0){
                   7910:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7911:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7912:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7913:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7914:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7915:                 c12=cv12/sqrt(v1*v2);
                   7916:                 /* Computing eigen value of matrix of covariance */
                   7917:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7918:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7919:                 if ((lc2 <0) || (lc1 <0) ){
                   7920:                   if(first2==1){
                   7921:                     first1=0;
                   7922:                     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);
                   7923:                   }
                   7924:                   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);
                   7925:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7926:                   /* lc2=fabs(lc2); */
                   7927:                 }
1.220     brouard  7928:                                                                
1.222     brouard  7929:                 /* Eigen vectors */
1.280     brouard  7930:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7931:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7932:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7933:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7934:                 }else
                   7935:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7936:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7937:                 v21=(lc1-v1)/cv12*v11;
                   7938:                 v12=-v21;
                   7939:                 v22=v11;
                   7940:                 tnalp=v21/v11;
                   7941:                 if(first1==1){
                   7942:                   first1=0;
                   7943:                   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);
                   7944:                 }
                   7945:                 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);
                   7946:                 /*printf(fignu*/
                   7947:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7948:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7949:                 if(first==1){
                   7950:                   first=0;
                   7951:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7952:                   fprintf(ficgp,"\nset parametric;unset label");
                   7953:                   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);
                   7954:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7955:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7956:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7957: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7958:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7959:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7960:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7961:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7962:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7963:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7964:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7965:                   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  7966:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7967:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7968:                 }else{
                   7969:                   first=0;
                   7970:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7971:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7972:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7973:                   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  7974:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7975:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7976:                 }/* if first */
                   7977:               } /* age mod 5 */
                   7978:             } /* end loop age */
                   7979:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7980:             first=1;
                   7981:           } /*l12 */
                   7982:         } /* k12 */
                   7983:        } /*l1 */
                   7984:      }/* k1 */
1.332     brouard  7985:    }  /* loop on combination of covariates j1 */
1.326     brouard  7986:    } /* loop on nres */
1.222     brouard  7987:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7988:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7989:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7990:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7991:    free_vector(xp,1,npar);
                   7992:    fclose(ficresprob);
                   7993:    fclose(ficresprobcov);
                   7994:    fclose(ficresprobcor);
                   7995:    fflush(ficgp);
                   7996:    fflush(fichtmcov);
                   7997:  }
1.126     brouard  7998: 
                   7999: 
                   8000: /******************* Printing html file ***********/
1.201     brouard  8001: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8002:                  int lastpass, int stepm, int weightopt, char model[],\
                   8003:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8004:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8005:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8006:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8007:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8008:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8009:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8010:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8011: </ul>");
1.319     brouard  8012: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8013: /* </ul>", model); */
1.214     brouard  8014:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8015:    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",
                   8016:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8017:    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  8018:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8019:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8020:    fprintf(fichtm,"\
                   8021:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8022:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8023:    fprintf(fichtm,"\
1.217     brouard  8024:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8025:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8026:    fprintf(fichtm,"\
1.288     brouard  8027:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8028:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8029:    fprintf(fichtm,"\
1.288     brouard  8030:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8031:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8032:    fprintf(fichtm,"\
1.211     brouard  8033:  - (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  8034:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8035:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8036:    if(prevfcast==1){
                   8037:      fprintf(fichtm,"\
                   8038:  - Prevalence projections by age and states:                           \
1.201     brouard  8039:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8040:    }
1.126     brouard  8041: 
                   8042: 
1.225     brouard  8043:    m=pow(2,cptcoveff);
1.222     brouard  8044:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8045: 
1.317     brouard  8046:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8047: 
                   8048:    jj1=0;
                   8049: 
                   8050:    fprintf(fichtm," \n<ul>");
1.337     brouard  8051:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8052:      /* k1=nres; */
1.338     brouard  8053:      k1=TKresult[nres];
                   8054:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8055:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8056:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8057:    /*     continue; */
1.264     brouard  8058:      jj1++;
                   8059:      if (cptcovn > 0) {
                   8060:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8061:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8062:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8063:        }
1.337     brouard  8064:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8065:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8066:        /* } */
                   8067:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8068:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8069:        /* } */
1.264     brouard  8070:        fprintf(fichtm,"\">");
                   8071:        
                   8072:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8073:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8074:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8075:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8076:        }
1.337     brouard  8077:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8078:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8079:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8080:        /* } */
                   8081:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8082:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8083:        /* } */
1.264     brouard  8084:        if(invalidvarcomb[k1]){
                   8085:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8086:         continue;
                   8087:        }
                   8088:        fprintf(fichtm,"</a></li>");
                   8089:      } /* cptcovn >0 */
                   8090:    }
1.317     brouard  8091:    fprintf(fichtm," \n</ul>");
1.264     brouard  8092: 
1.222     brouard  8093:    jj1=0;
1.237     brouard  8094: 
1.337     brouard  8095:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8096:      /* k1=nres; */
1.338     brouard  8097:      k1=TKresult[nres];
                   8098:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8099:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8100:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8101:    /*     continue; */
1.220     brouard  8102: 
1.222     brouard  8103:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8104:      jj1++;
                   8105:      if (cptcovn > 0) {
1.264     brouard  8106:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8107:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8108:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8109:        }
1.337     brouard  8110:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8111:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8112:        /* } */
1.264     brouard  8113:        fprintf(fichtm,"\"</a>");
                   8114:  
1.222     brouard  8115:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8116:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8117:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8118:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8119:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8120:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8121:        }
1.230     brouard  8122:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8123:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8124:        if(invalidvarcomb[k1]){
                   8125:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8126:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8127:         continue;
                   8128:        }
                   8129:      }
                   8130:      /* aij, bij */
1.259     brouard  8131:      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  8132: <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  8133:      /* Pij */
1.241     brouard  8134:      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> \
                   8135: <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  8136:      /* Quasi-incidences */
                   8137:      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  8138:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8139:  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  8140: 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> \
                   8141: <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  8142:      /* Survival functions (period) in state j */
                   8143:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8144:        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);
                   8145:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8146:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8147:      }
                   8148:      /* State specific survival functions (period) */
                   8149:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8150:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8151:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8152:  <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);
                   8153:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8154:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8155:      }
1.288     brouard  8156:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8157:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8158:        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  8159:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8160:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8161:      }
1.296     brouard  8162:      if(prevbcast==1){
1.288     brouard  8163:        /* Backward prevalence in each health state */
1.222     brouard  8164:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8165:         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);
                   8166:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8167:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8168:        }
1.217     brouard  8169:      }
1.222     brouard  8170:      if(prevfcast==1){
1.288     brouard  8171:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8172:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8173:         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);
                   8174:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8175:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8176:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8177:        }
                   8178:      }
1.296     brouard  8179:      if(prevbcast==1){
1.268     brouard  8180:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8181:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8182:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8183:  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 \
                   8184:  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  8185: 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);
                   8186:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8187:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8188:        }
                   8189:      }
1.220     brouard  8190:         
1.222     brouard  8191:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8192:        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);
                   8193:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8194:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8195:      }
                   8196:      /* } /\* end i1 *\/ */
1.337     brouard  8197:    }/* End k1=nres */
1.222     brouard  8198:    fprintf(fichtm,"</ul>");
1.126     brouard  8199: 
1.222     brouard  8200:    fprintf(fichtm,"\
1.126     brouard  8201: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8202:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8203:  - 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  8204: But because parameters are usually highly correlated (a higher incidence of disability \
                   8205: and a higher incidence of recovery can give very close observed transition) it might \
                   8206: be very useful to look not only at linear confidence intervals estimated from the \
                   8207: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8208: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8209: covariance matrix of the one-step probabilities. \
                   8210: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8211: 
1.222     brouard  8212:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8213:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8214:    fprintf(fichtm,"\
1.126     brouard  8215:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8216:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8217: 
1.222     brouard  8218:    fprintf(fichtm,"\
1.126     brouard  8219:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8220:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8221:    fprintf(fichtm,"\
1.126     brouard  8222:  - 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): \
                   8223:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8224:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8225:    fprintf(fichtm,"\
1.126     brouard  8226:  - (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): \
                   8227:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8228:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8229:    fprintf(fichtm,"\
1.288     brouard  8230:  - 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  8231:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8232:    fprintf(fichtm,"\
1.128     brouard  8233:  - 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  8234:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8235:    fprintf(fichtm,"\
1.288     brouard  8236:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8237:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8238: 
                   8239: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8240: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8241: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8242: /*     <br>",fileres,fileres,fileres,fileres); */
                   8243: /*  else  */
1.338     brouard  8244: /*    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  8245:    fflush(fichtm);
1.126     brouard  8246: 
1.225     brouard  8247:    m=pow(2,cptcoveff);
1.222     brouard  8248:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8249: 
1.317     brouard  8250:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8251: 
                   8252:   jj1=0;
                   8253: 
                   8254:    fprintf(fichtm," \n<ul>");
1.337     brouard  8255:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8256:      /* k1=nres; */
1.338     brouard  8257:      k1=TKresult[nres];
1.337     brouard  8258:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8259:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8260:      /*   continue; */
1.317     brouard  8261:      jj1++;
                   8262:      if (cptcovn > 0) {
                   8263:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8264:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8265:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8266:        }
                   8267:        fprintf(fichtm,"\">");
                   8268:        
                   8269:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8270:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8271:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8272:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8273:        }
                   8274:        if(invalidvarcomb[k1]){
                   8275:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8276:         continue;
                   8277:        }
                   8278:        fprintf(fichtm,"</a></li>");
                   8279:      } /* cptcovn >0 */
1.337     brouard  8280:    } /* End nres */
1.317     brouard  8281:    fprintf(fichtm," \n</ul>");
                   8282: 
1.222     brouard  8283:    jj1=0;
1.237     brouard  8284: 
1.241     brouard  8285:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8286:      /* k1=nres; */
1.338     brouard  8287:      k1=TKresult[nres];
                   8288:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8289:      /* for(k1=1; k1<=m;k1++){ */
                   8290:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8291:      /*   continue; */
1.222     brouard  8292:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8293:      jj1++;
1.126     brouard  8294:      if (cptcovn > 0) {
1.317     brouard  8295:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8296:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8297:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8298:        }
                   8299:        fprintf(fichtm,"\"</a>");
                   8300:        
1.126     brouard  8301:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8302:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8303:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8304:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8305:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8306:        }
1.237     brouard  8307: 
1.338     brouard  8308:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8309: 
1.222     brouard  8310:        if(invalidvarcomb[k1]){
                   8311:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8312:         continue;
                   8313:        }
1.337     brouard  8314:      } /* If cptcovn >0 */
1.126     brouard  8315:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8316:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8317: 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);
                   8318:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8319:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8320:      }
                   8321:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8322: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8323: true period expectancies (those weighted with period prevalences are also\
                   8324:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8325:  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);
                   8326:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8327:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8328:      /* } /\* end i1 *\/ */
1.241     brouard  8329:   }/* End nres */
1.222     brouard  8330:    fprintf(fichtm,"</ul>");
                   8331:    fflush(fichtm);
1.126     brouard  8332: }
                   8333: 
                   8334: /******************* Gnuplot file **************/
1.296     brouard  8335: 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  8336: 
                   8337:   char dirfileres[132],optfileres[132];
1.264     brouard  8338:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8339:   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  8340:   int lv=0, vlv=0, kl=0;
1.130     brouard  8341:   int ng=0;
1.201     brouard  8342:   int vpopbased;
1.223     brouard  8343:   int ioffset; /* variable offset for columns */
1.270     brouard  8344:   int iyearc=1; /* variable column for year of projection  */
                   8345:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8346:   int nres=0; /* Index of resultline */
1.266     brouard  8347:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8348: 
1.126     brouard  8349: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8350: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8351: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8352: /*   } */
                   8353: 
                   8354:   /*#ifdef windows */
                   8355:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8356:   /*#endif */
1.225     brouard  8357:   m=pow(2,cptcoveff);
1.126     brouard  8358: 
1.274     brouard  8359:   /* diagram of the model */
                   8360:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8361:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8362:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8363:   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);
                   8364: 
1.343     brouard  8365:   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  8366:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8367:   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);
                   8368:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8369:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8370:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8371:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8372: 
1.202     brouard  8373:   /* Contribution to likelihood */
                   8374:   /* Plot the probability implied in the likelihood */
1.223     brouard  8375:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8376:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8377:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8378:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8379: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8380:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8381: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8382:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8383:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8384:   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));
                   8385:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8386:   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));
                   8387:   for (i=1; i<= nlstate ; i ++) {
                   8388:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8389:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8390:     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);
                   8391:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8392:       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);
                   8393:     }
                   8394:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8395:   }
                   8396:   /* 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 */               
                   8397:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8398:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8399:   fprintf(ficgp,"\nset out;unset log\n");
                   8400:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8401: 
1.343     brouard  8402:   /* Plot the probability implied in the likelihood by covariate value */
                   8403:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8404:   /* if(debugILK==1){ */
                   8405:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8406:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8407:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350   ! brouard  8408:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
        !          8409:     k=19+kf;/*offset because there are 19 columns in the ILK_ file */
1.343     brouard  8410:     for (i=1; i<= nlstate ; i ++) {
                   8411:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8412:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8413:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8414:        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);
                   8415:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8416:          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);
                   8417:        }
                   8418:       }else{
                   8419:        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);
                   8420:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8421:          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);
                   8422:        }
1.343     brouard  8423:       }
                   8424:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8425:     }
                   8426:   } /* End of each covariate dummy */
                   8427:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8428:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8429:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8430:      *  varying                   1     2                                 3       4        5
                   8431:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8432:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8433:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8434:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8435:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8436:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8437:      */
                   8438:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8439:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8440:     /* 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]); */
                   8441:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8442:       /* printf(" %d",ipos); */
                   8443:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8444:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8445:       kk++; /* Position of the ncovv column in ILK_ */
                   8446:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8447:       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)  */
                   8448:        for (i=1; i<= nlstate ; i ++) {
                   8449:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8450:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8451: 
1.348     brouard  8452:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8453:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8454:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8455:            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);
                   8456:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8457:              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);
                   8458:            }
                   8459:          }else{
                   8460:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8461:            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);
                   8462:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8463:              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);
                   8464:            }
                   8465:          }
                   8466:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8467:        }
                   8468:       }/* End if dummy varying */
                   8469:     }else{ /*Product */
                   8470:       /* printf("*"); */
                   8471:       /* fprintf(ficresilk,"*"); */
                   8472:     }
                   8473:     iposold=ipos;
                   8474:   } /* For each time varying covariate */
                   8475:   /* } /\* debugILK==1 *\/ */
                   8476:   /* 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 */               
                   8477:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8478:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8479:   fprintf(ficgp,"\nset out;unset log\n");
                   8480:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8481: 
                   8482: 
                   8483:   
1.126     brouard  8484:   strcpy(dirfileres,optionfilefiname);
                   8485:   strcpy(optfileres,"vpl");
1.223     brouard  8486:   /* 1eme*/
1.238     brouard  8487:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8488:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8489:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8490:        k1=TKresult[nres];
1.338     brouard  8491:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8492:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8493:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8494:        /*   continue; */
1.238     brouard  8495:        /* We are interested in selected combination by the resultline */
1.246     brouard  8496:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8497:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8498:        strcpy(gplotlabel,"(");
1.337     brouard  8499:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8500:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8501:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8502: 
                   8503:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8504:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8505:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8506:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8507:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8508:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8509:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8510:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8511:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8512:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8513:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8514:        /* } */
                   8515:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8516:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8517:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8518:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8519:        }
                   8520:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8521:        /* printf("\n#\n"); */
1.238     brouard  8522:        fprintf(ficgp,"\n#\n");
                   8523:        if(invalidvarcomb[k1]){
1.260     brouard  8524:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8525:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8526:          continue;
                   8527:        }
1.235     brouard  8528:       
1.241     brouard  8529:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8530:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8531:        /* 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  8532:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8533:        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);
                   8534:        /* 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); */
                   8535:       /* k1-1 error should be nres-1*/
1.238     brouard  8536:        for (i=1; i<= nlstate ; i ++) {
                   8537:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8538:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8539:        }
1.288     brouard  8540:        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  8541:        for (i=1; i<= nlstate ; i ++) {
                   8542:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8543:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8544:        } 
1.260     brouard  8545:        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  8546:        for (i=1; i<= nlstate ; i ++) {
                   8547:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8548:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8549:        }  
1.265     brouard  8550:        /* 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)); */
                   8551:        
                   8552:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8553:         if(cptcoveff ==0){
1.271     brouard  8554:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8555:        }else{
                   8556:          kl=0;
                   8557:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8558:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8559:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8560:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8561:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8562:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8563:            vlv= nbcode[Tvaraff[k]][lv];
                   8564:            kl++;
                   8565:            /* 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 *\/ */
                   8566:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8567:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8568:            /* ''  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*/
                   8569:            if(k==cptcoveff){
                   8570:              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], \
                   8571:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8572:            }else{
                   8573:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8574:              kl++;
                   8575:            }
                   8576:          } /* end covariate */
                   8577:        } /* end if no covariate */
                   8578: 
1.296     brouard  8579:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8580:          /* 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  8581:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8582:          if(cptcoveff ==0){
1.245     brouard  8583:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8584:          }else{
                   8585:            kl=0;
                   8586:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8587:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8588:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8589:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8590:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8591:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8592:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8593:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8594:              kl++;
1.238     brouard  8595:              /* 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 *\/ */
                   8596:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8597:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8598:              /* ''  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*/
                   8599:              if(k==cptcoveff){
1.245     brouard  8600:                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  8601:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8602:              }else{
1.332     brouard  8603:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8604:                kl++;
                   8605:              }
                   8606:            } /* end covariate */
                   8607:          } /* end if no covariate */
1.296     brouard  8608:          if(prevbcast == 1){
1.268     brouard  8609:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8610:            /* k1-1 error should be nres-1*/
                   8611:            for (i=1; i<= nlstate ; i ++) {
                   8612:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8613:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8614:            }
1.271     brouard  8615:            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  8616:            for (i=1; i<= nlstate ; i ++) {
                   8617:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8618:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8619:            } 
1.276     brouard  8620:            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  8621:            for (i=1; i<= nlstate ; i ++) {
                   8622:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8623:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8624:            } 
1.274     brouard  8625:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8626:          } /* end if backprojcast */
1.296     brouard  8627:        } /* end if prevbcast */
1.276     brouard  8628:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8629:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8630:       } /* nres */
1.337     brouard  8631:     /* } /\* k1 *\/ */
1.201     brouard  8632:   } /* cpt */
1.235     brouard  8633: 
                   8634:   
1.126     brouard  8635:   /*2 eme*/
1.337     brouard  8636:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8637:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8638:       k1=TKresult[nres];
1.338     brouard  8639:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8640:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8641:       /*       continue; */
1.238     brouard  8642:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8643:       strcpy(gplotlabel,"(");
1.337     brouard  8644:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8645:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8646:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8647:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8648:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8649:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8650:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8651:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8652:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8653:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8654:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8655:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8656:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8657:       /* } */
                   8658:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8659:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8660:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8661:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8662:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8663:       }
1.264     brouard  8664:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8665:       fprintf(ficgp,"\n#\n");
1.223     brouard  8666:       if(invalidvarcomb[k1]){
                   8667:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8668:        continue;
                   8669:       }
1.219     brouard  8670:                        
1.241     brouard  8671:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8672:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8673:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8674:        if(vpopbased==0){
1.238     brouard  8675:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8676:        }else
1.238     brouard  8677:          fprintf(ficgp,"\nreplot ");
                   8678:        for (i=1; i<= nlstate+1 ; i ++) {
                   8679:          k=2*i;
1.261     brouard  8680:          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  8681:          for (j=1; j<= nlstate+1 ; j ++) {
                   8682:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8683:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8684:          }   
                   8685:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8686:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8687:          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  8688:          for (j=1; j<= nlstate+1 ; j ++) {
                   8689:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8690:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8691:          }   
                   8692:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8693:          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  8694:          for (j=1; j<= nlstate+1 ; j ++) {
                   8695:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8696:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8697:          }   
                   8698:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8699:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8700:        } /* state */
                   8701:       } /* vpopbased */
1.264     brouard  8702:       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  8703:     } /* end nres */
1.337     brouard  8704:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8705:        
                   8706:        
                   8707:   /*3eme*/
1.337     brouard  8708:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8709:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8710:       k1=TKresult[nres];
1.338     brouard  8711:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8712:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8713:       /*       continue; */
1.238     brouard  8714: 
1.332     brouard  8715:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8716:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8717:        strcpy(gplotlabel,"(");
1.337     brouard  8718:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8719:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8720:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8721:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8722:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8723:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8724:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8725:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8726:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8727:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8728:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8729:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8730:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8731:        /* } */
                   8732:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8733:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8734:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8735:        }
1.264     brouard  8736:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8737:        fprintf(ficgp,"\n#\n");
                   8738:        if(invalidvarcomb[k1]){
                   8739:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8740:          continue;
                   8741:        }
                   8742:                        
                   8743:        /*       k=2+nlstate*(2*cpt-2); */
                   8744:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8745:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8746:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8747:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8748: 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  8749:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8750:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8751:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8752:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8753:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8754:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8755:                                
1.238     brouard  8756:        */
                   8757:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8758:          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  8759:          /*    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  8760:                                
1.238     brouard  8761:        } 
1.261     brouard  8762:        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  8763:       }
1.264     brouard  8764:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8765:     } /* end nres */
1.337     brouard  8766:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8767:   
1.223     brouard  8768:   /* 4eme */
1.201     brouard  8769:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8770:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8771:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8772:       k1=TKresult[nres];
1.338     brouard  8773:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8774:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8775:       /*       continue; */
1.238     brouard  8776:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8777:        strcpy(gplotlabel,"(");
1.337     brouard  8778:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8779:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8780:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8781:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8782:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8783:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8784:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8785:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8786:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8787:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8788:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8789:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8790:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8791:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8792:        /* } */
                   8793:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8794:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8795:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8796:        }       
1.264     brouard  8797:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8798:        fprintf(ficgp,"\n#\n");
                   8799:        if(invalidvarcomb[k1]){
                   8800:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8801:          continue;
1.223     brouard  8802:        }
1.238     brouard  8803:       
1.241     brouard  8804:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8805:        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  8806:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8807: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8808:        k=3;
                   8809:        for (i=1; i<= nlstate ; i ++){
                   8810:          if(i==1){
                   8811:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8812:          }else{
                   8813:            fprintf(ficgp,", '' ");
                   8814:          }
                   8815:          l=(nlstate+ndeath)*(i-1)+1;
                   8816:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8817:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8818:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8819:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8820:        } /* nlstate */
1.264     brouard  8821:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8822:       } /* end cpt state*/ 
                   8823:     } /* end nres */
1.337     brouard  8824:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8825: 
1.220     brouard  8826: /* 5eme */
1.201     brouard  8827:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8828:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8829:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8830:       k1=TKresult[nres];
1.338     brouard  8831:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8832:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8833:       /*       continue; */
1.238     brouard  8834:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8835:        strcpy(gplotlabel,"(");
1.238     brouard  8836:        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  8837:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8838:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8839:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8840:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8841:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8842:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8843:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8844:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8845:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8846:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8847:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8848:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8849:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8850:        /* } */
                   8851:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8852:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8853:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8854:        }       
1.264     brouard  8855:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8856:        fprintf(ficgp,"\n#\n");
                   8857:        if(invalidvarcomb[k1]){
                   8858:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8859:          continue;
                   8860:        }
1.227     brouard  8861:       
1.241     brouard  8862:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8863:        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  8864:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8865: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8866:        k=3;
                   8867:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8868:          if(j==1)
                   8869:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8870:          else
                   8871:            fprintf(ficgp,", '' ");
                   8872:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8873:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8874:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8875:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8876:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8877:        } /* nlstate */
                   8878:        fprintf(ficgp,", '' ");
                   8879:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8880:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8881:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8882:          if(j < nlstate)
                   8883:            fprintf(ficgp,"$%d +",k+l);
                   8884:          else
                   8885:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8886:        }
1.264     brouard  8887:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8888:       } /* end cpt state*/ 
1.337     brouard  8889:     /* } /\* end covariate *\/   */
1.238     brouard  8890:   } /* end nres */
1.227     brouard  8891:   
1.220     brouard  8892: /* 6eme */
1.202     brouard  8893:   /* CV preval stable (period) for each covariate */
1.337     brouard  8894:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8895:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8896:      k1=TKresult[nres];
1.338     brouard  8897:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8898:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8899:      /*  continue; */
1.255     brouard  8900:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8901:       strcpy(gplotlabel,"(");      
1.288     brouard  8902:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8903:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8904:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8905:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8906:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8907:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8908:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8909:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8910:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8911:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8912:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8913:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8914:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8915:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8916:       /* } */
                   8917:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8918:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8919:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8920:       }        
1.264     brouard  8921:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8922:       fprintf(ficgp,"\n#\n");
1.223     brouard  8923:       if(invalidvarcomb[k1]){
1.227     brouard  8924:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8925:        continue;
1.223     brouard  8926:       }
1.227     brouard  8927:       
1.241     brouard  8928:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8929:       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  8930:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8931: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8932:       k=3; /* Offset */
1.255     brouard  8933:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8934:        if(i==1)
                   8935:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8936:        else
                   8937:          fprintf(ficgp,", '' ");
1.255     brouard  8938:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8939:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8940:        for (j=2; j<= nlstate ; j ++)
                   8941:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8942:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8943:       } /* nlstate */
1.264     brouard  8944:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8945:     } /* end cpt state*/ 
                   8946:   } /* end covariate */  
1.227     brouard  8947:   
                   8948:   
1.220     brouard  8949: /* 7eme */
1.296     brouard  8950:   if(prevbcast == 1){
1.288     brouard  8951:     /* CV backward prevalence  for each covariate */
1.337     brouard  8952:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8953:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8954:       k1=TKresult[nres];
1.338     brouard  8955:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8956:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8957:       /*       continue; */
1.268     brouard  8958:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8959:        strcpy(gplotlabel,"(");      
1.288     brouard  8960:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8961:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8962:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8963:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8964:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8965:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8966:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8967:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8968:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8969:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8970:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8971:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8972:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8973:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8974:        /* } */
                   8975:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8976:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8977:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8978:        }       
1.264     brouard  8979:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8980:        fprintf(ficgp,"\n#\n");
                   8981:        if(invalidvarcomb[k1]){
                   8982:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8983:          continue;
                   8984:        }
                   8985:        
1.241     brouard  8986:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8987:        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  8988:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8989: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8990:        k=3; /* Offset */
1.268     brouard  8991:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8992:          if(i==1)
                   8993:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8994:          else
                   8995:            fprintf(ficgp,", '' ");
                   8996:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8997:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8998:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8999:          /* 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  9000:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9001:          /* for (j=2; j<= nlstate ; j ++) */
                   9002:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9003:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9004:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9005:        } /* nlstate */
1.264     brouard  9006:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9007:       } /* end cpt state*/ 
                   9008:     } /* end covariate */  
1.296     brouard  9009:   } /* End if prevbcast */
1.218     brouard  9010:   
1.223     brouard  9011:   /* 8eme */
1.218     brouard  9012:   if(prevfcast==1){
1.288     brouard  9013:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9014:     
1.337     brouard  9015:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9016:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9017:       k1=TKresult[nres];
1.338     brouard  9018:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9019:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9020:       /*       continue; */
1.211     brouard  9021:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9022:        strcpy(gplotlabel,"(");      
1.288     brouard  9023:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9024:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9025:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9026:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9027:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9028:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9029:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9030:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9031:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9032:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9033:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9034:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9035:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9036:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9037:        /* } */
                   9038:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9039:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9040:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9041:        }       
1.264     brouard  9042:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9043:        fprintf(ficgp,"\n#\n");
                   9044:        if(invalidvarcomb[k1]){
                   9045:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9046:          continue;
                   9047:        }
                   9048:        
                   9049:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9050:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9051:        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  9052:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9053: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9054: 
                   9055:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9056:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9057:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9058:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9059:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9060:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9061:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9062:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9063:          if(i==istart){
1.227     brouard  9064:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9065:          }else{
                   9066:            fprintf(ficgp,",\\\n '' ");
                   9067:          }
                   9068:          if(cptcoveff ==0){ /* No covariate */
                   9069:            ioffset=2; /* Age is in 2 */
                   9070:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9071:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9072:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9073:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9074:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9075:            if(i==nlstate+1){
1.270     brouard  9076:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9077:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9078:              fprintf(ficgp,",\\\n '' ");
                   9079:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9080:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9081:                     offyear,                           \
1.268     brouard  9082:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9083:            }else
1.227     brouard  9084:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9085:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9086:          }else{ /* more than 2 covariates */
1.270     brouard  9087:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9088:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9089:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9090:            iyearc=ioffset-1;
                   9091:            iagec=ioffset;
1.227     brouard  9092:            fprintf(ficgp," u %d:(",ioffset); 
                   9093:            kl=0;
                   9094:            strcpy(gplotcondition,"(");
                   9095:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  9096:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9097:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  9098:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9099:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9100:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9101:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9102:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  9103:              kl++;
                   9104:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   9105:              kl++;
                   9106:              if(k <cptcoveff && cptcoveff>1)
                   9107:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9108:            }
                   9109:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9110:            /* 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 *\/ */
                   9111:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9112:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9113:            /* ''  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*/
                   9114:            if(i==nlstate+1){
1.270     brouard  9115:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9116:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9117:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9118:              fprintf(ficgp," u %d:(",iagec); 
                   9119:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9120:                      iyearc, iagec, offyear,                           \
                   9121:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9122: /*  '' 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  9123:            }else{
                   9124:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9125:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9126:            }
                   9127:          } /* end if covariate */
                   9128:        } /* nlstate */
1.264     brouard  9129:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9130:       } /* end cpt state*/
                   9131:     } /* end covariate */
                   9132:   } /* End if prevfcast */
1.227     brouard  9133:   
1.296     brouard  9134:   if(prevbcast==1){
1.268     brouard  9135:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9136:     
1.337     brouard  9137:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9138:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9139:      k1=TKresult[nres];
1.338     brouard  9140:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9141:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9142:        /*      continue; */
1.268     brouard  9143:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9144:        strcpy(gplotlabel,"(");      
                   9145:        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  9146:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9147:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9148:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9149:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9150:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9151:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9152:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9153:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9154:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9155:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9156:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9157:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9158:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9159:        /* } */
                   9160:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9161:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9162:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9163:        }       
                   9164:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9165:        fprintf(ficgp,"\n#\n");
                   9166:        if(invalidvarcomb[k1]){
                   9167:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9168:          continue;
                   9169:        }
                   9170:        
                   9171:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9172:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9173:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9174:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9175: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9176: 
                   9177:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9178:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9179:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9180:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9181:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9182:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9183:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9184:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9185:          if(i==istart){
                   9186:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9187:          }else{
                   9188:            fprintf(ficgp,",\\\n '' ");
                   9189:          }
                   9190:          if(cptcoveff ==0){ /* No covariate */
                   9191:            ioffset=2; /* Age is in 2 */
                   9192:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9193:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9194:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9195:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9196:            fprintf(ficgp," u %d:(", ioffset); 
                   9197:            if(i==nlstate+1){
1.270     brouard  9198:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9199:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9200:              fprintf(ficgp,",\\\n '' ");
                   9201:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9202:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9203:                     offbyear,                          \
                   9204:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9205:            }else
                   9206:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9207:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9208:          }else{ /* more than 2 covariates */
1.270     brouard  9209:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9210:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9211:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9212:            iyearc=ioffset-1;
                   9213:            iagec=ioffset;
1.268     brouard  9214:            fprintf(ficgp," u %d:(",ioffset); 
                   9215:            kl=0;
                   9216:            strcpy(gplotcondition,"(");
1.337     brouard  9217:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9218:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9219:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9220:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9221:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9222:                lv=Tvresult[nres][k];
                   9223:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9224:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9225:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9226:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9227:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9228:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9229:                kl++;
                   9230:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9231:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9232:                kl++;
1.338     brouard  9233:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9234:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9235:              }
1.268     brouard  9236:            }
                   9237:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9238:            /* 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 *\/ */
                   9239:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9240:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9241:            /* ''  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*/
                   9242:            if(i==nlstate+1){
1.270     brouard  9243:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9244:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9245:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9246:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9247:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9248:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9249:                      iyearc,iagec,offbyear,                            \
                   9250:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9251: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9252:            }else{
                   9253:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9254:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9255:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9256:            }
                   9257:          } /* end if covariate */
                   9258:        } /* nlstate */
                   9259:        fprintf(ficgp,"\nset out; unset label;\n");
                   9260:       } /* end cpt state*/
                   9261:     } /* end covariate */
1.296     brouard  9262:   } /* End if prevbcast */
1.268     brouard  9263:   
1.227     brouard  9264:   
1.238     brouard  9265:   /* 9eme writing MLE parameters */
                   9266:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9267:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9268:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9269:     for(k=1; k <=(nlstate+ndeath); k++){
                   9270:       if (k != i) {
1.227     brouard  9271:        fprintf(ficgp,"#   current state %d\n",k);
                   9272:        for(j=1; j <=ncovmodel; j++){
                   9273:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9274:          jk++; 
                   9275:        }
                   9276:        fprintf(ficgp,"\n");
1.126     brouard  9277:       }
                   9278:     }
1.223     brouard  9279:   }
1.187     brouard  9280:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9281:   
1.145     brouard  9282:   /*goto avoid;*/
1.238     brouard  9283:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9284:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9285:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9286:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9287:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9288:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9289:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9290:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9291:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9292:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9293:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9294:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9295:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9296:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9297:   fprintf(ficgp,"#\n");
1.223     brouard  9298:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9299:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9300:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9301:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9302:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9303:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9304:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9305:      /* k1=nres; */
1.338     brouard  9306:       k1=TKresult[nres];
                   9307:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9308:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9309:       strcpy(gplotlabel,"(");
1.276     brouard  9310:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9311:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9312:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9313:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9314:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9315:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9316:       }
                   9317:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9318:       /*       continue; */
                   9319:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9320:       /* strcpy(gplotlabel,"("); */
                   9321:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9322:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9323:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9324:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9325:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9326:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9327:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9328:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9329:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9330:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9331:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9332:       /* } */
                   9333:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9334:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9335:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9336:       /* }      */
1.264     brouard  9337:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9338:       fprintf(ficgp,"\n#\n");
1.264     brouard  9339:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9340:       fprintf(ficgp,"\nset key outside ");
                   9341:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9342:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9343:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9344:       if (ng==1){
                   9345:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9346:        fprintf(ficgp,"\nunset log y");
                   9347:       }else if (ng==2){
                   9348:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9349:        fprintf(ficgp,"\nset log y");
                   9350:       }else if (ng==3){
                   9351:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9352:        fprintf(ficgp,"\nset log y");
                   9353:       }else
                   9354:        fprintf(ficgp,"\nunset title ");
                   9355:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9356:       i=1;
                   9357:       for(k2=1; k2<=nlstate; k2++) {
                   9358:        k3=i;
                   9359:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9360:          if (k != k2){
                   9361:            switch( ng) {
                   9362:            case 1:
                   9363:              if(nagesqr==0)
                   9364:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9365:              else /* nagesqr =1 */
                   9366:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9367:              break;
                   9368:            case 2: /* ng=2 */
                   9369:              if(nagesqr==0)
                   9370:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9371:              else /* nagesqr =1 */
                   9372:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9373:              break;
                   9374:            case 3:
                   9375:              if(nagesqr==0)
                   9376:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9377:              else /* nagesqr =1 */
                   9378:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9379:              break;
                   9380:            }
                   9381:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9382:            ijp=1; /* product no age */
                   9383:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9384:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9385:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9386:              switch(Typevar[j]){
                   9387:              case 1:
                   9388:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9389:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9390:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9391:                      if(DummyV[j]==0){/* Bug valgrind */
                   9392:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9393:                      }else{ /* quantitative */
                   9394:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9395:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9396:                      }
                   9397:                      ij++;
1.268     brouard  9398:                    }
1.237     brouard  9399:                  }
1.329     brouard  9400:                }
                   9401:                break;
                   9402:              case 2:
                   9403:                if(cptcovprod >0){
                   9404:                  if(j==Tprod[ijp]) { /* */ 
                   9405:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9406:                    if(ijp <=cptcovprod) { /* Product */
                   9407:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9408:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9409:                          /* 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)]); */
                   9410:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9411:                        }else{ /* Vn is dummy and Vm is quanti */
                   9412:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9413:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9414:                        }
                   9415:                      }else{ /* Vn*Vm Vn is quanti */
                   9416:                        if(DummyV[Tvard[ijp][2]]==0){
                   9417:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9418:                        }else{ /* Both quanti */
                   9419:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9420:                        }
1.268     brouard  9421:                      }
1.329     brouard  9422:                      ijp++;
1.237     brouard  9423:                    }
1.329     brouard  9424:                  } /* end Tprod */
                   9425:                }
                   9426:                break;
1.349     brouard  9427:              case 3:
                   9428:                if(cptcovdageprod >0){
                   9429:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9430:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350   ! brouard  9431:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
        !          9432:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
        !          9433:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9434:                          /* 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)]); */
                   9435:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9436:                        }else{ /* Vn is dummy and Vm is quanti */
                   9437:                          /* 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  9438:                          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  9439:                        }
1.350   ! brouard  9440:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9441:                        if(DummyV[Tvard[ijp][2]]==0){
1.350   ! brouard  9442:                          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  9443:                        }else{ /* Both quanti */
1.350   ! brouard  9444:                          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  9445:                        }
                   9446:                      }
                   9447:                      ijp++;
                   9448:                    }
                   9449:                    /* } */ /* end Tprod */
                   9450:                }
                   9451:                break;
1.329     brouard  9452:              case 0:
                   9453:                /* simple covariate */
1.264     brouard  9454:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9455:                if(Dummy[j]==0){
                   9456:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9457:                }else{ /* quantitative */
                   9458:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9459:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9460:                }
1.329     brouard  9461:               /* end simple */
                   9462:                break;
                   9463:              default:
                   9464:                break;
                   9465:              } /* end switch */
1.237     brouard  9466:            } /* end j */
1.329     brouard  9467:          }else{ /* k=k2 */
                   9468:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9469:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9470:            }else
                   9471:              i=i-ncovmodel;
1.223     brouard  9472:          }
1.227     brouard  9473:          
1.223     brouard  9474:          if(ng != 1){
                   9475:            fprintf(ficgp,")/(1");
1.227     brouard  9476:            
1.264     brouard  9477:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9478:              if(nagesqr==0)
1.264     brouard  9479:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9480:              else /* nagesqr =1 */
1.264     brouard  9481:                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  9482:               
1.223     brouard  9483:              ij=1;
1.329     brouard  9484:              ijp=1;
                   9485:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9486:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9487:                switch(Typevar[j]){
                   9488:                case 1:
                   9489:                  if(cptcovage >0){ 
                   9490:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9491:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9492:                        if(DummyV[j]==0){/* Bug valgrind */
                   9493:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9494:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9495:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9496:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9497:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9498:                        }else{ /* quantitative */
                   9499:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9500:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9501:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9502:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9503:                        }
                   9504:                        ij++;
                   9505:                      }
                   9506:                    }
                   9507:                  }
                   9508:                  break;
                   9509:                case 2:
                   9510:                  if(cptcovprod >0){
                   9511:                    if(j==Tprod[ijp]) { /* */ 
                   9512:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9513:                      if(ijp <=cptcovprod) { /* Product */
                   9514:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9515:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9516:                            /* 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)]); */
                   9517:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9518:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9519:                          }else{ /* Vn is dummy and Vm is quanti */
                   9520:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9521:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9522:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9523:                          }
                   9524:                        }else{ /* Vn*Vm Vn is quanti */
                   9525:                          if(DummyV[Tvard[ijp][2]]==0){
                   9526:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9527:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9528:                          }else{ /* Both quanti */
                   9529:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9530:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9531:                          } 
                   9532:                        }
                   9533:                        ijp++;
                   9534:                      }
                   9535:                    } /* end Tprod */
                   9536:                  } /* end if */
                   9537:                  break;
1.349     brouard  9538:                case 3:
                   9539:                  if(cptcovdageprod >0){
                   9540:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9541:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9542:                      if(ijp <=cptcovprod) { /* Product */
1.350   ! brouard  9543:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
        !          9544:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9545:                            /* 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  9546:                            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  9547:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9548:                          }else{ /* Vn is dummy and Vm is quanti */
                   9549:                            /* 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  9550:                            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  9551:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9552:                          }
                   9553:                        }else{ /* Vn*Vm Vn is quanti */
1.350   ! brouard  9554:                          if(DummyV[Tvardk[ijp][2]]==0){
        !          9555:                            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  9556:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9557:                          }else{ /* Both quanti */
1.350   ! brouard  9558:                            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  9559:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9560:                          } 
                   9561:                        }
                   9562:                        ijp++;
                   9563:                      }
                   9564:                    /* } /\* end Tprod *\/ */
                   9565:                  } /* end if */
                   9566:                  break;
1.329     brouard  9567:                case 0: 
                   9568:                  /* simple covariate */
                   9569:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9570:                  if(Dummy[j]==0){
                   9571:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9572:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9573:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9574:                  }else{ /* quantitative */
                   9575:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9576:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9577:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9578:                  }
                   9579:                  /* end simple */
                   9580:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9581:                  break;
                   9582:                default:
                   9583:                  break;
                   9584:                } /* end switch */
1.223     brouard  9585:              }
                   9586:              fprintf(ficgp,")");
                   9587:            }
                   9588:            fprintf(ficgp,")");
                   9589:            if(ng ==2)
1.276     brouard  9590:              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  9591:            else /* ng= 3 */
1.276     brouard  9592:              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  9593:           }else{ /* end ng <> 1 */
1.223     brouard  9594:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9595:              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  9596:          }
                   9597:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9598:            fprintf(ficgp,",");
                   9599:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9600:            fprintf(ficgp,",");
                   9601:          i=i+ncovmodel;
                   9602:        } /* end k */
                   9603:       } /* end k2 */
1.276     brouard  9604:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9605:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9606:     } /* end resultline */
1.223     brouard  9607:   } /* end ng */
                   9608:   /* avoid: */
                   9609:   fflush(ficgp); 
1.126     brouard  9610: }  /* end gnuplot */
                   9611: 
                   9612: 
                   9613: /*************** Moving average **************/
1.219     brouard  9614: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9615:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9616:    
1.222     brouard  9617:    int i, cpt, cptcod;
                   9618:    int modcovmax =1;
                   9619:    int mobilavrange, mob;
                   9620:    int iage=0;
1.288     brouard  9621:    int firstA1=0, firstA2=0;
1.222     brouard  9622: 
1.266     brouard  9623:    double sum=0., sumr=0.;
1.222     brouard  9624:    double age;
1.266     brouard  9625:    double *sumnewp, *sumnewm, *sumnewmr;
                   9626:    double *agemingood, *agemaxgood; 
                   9627:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9628:   
                   9629:   
1.278     brouard  9630:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9631:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9632: 
                   9633:    sumnewp = vector(1,ncovcombmax);
                   9634:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9635:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9636:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9637:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9638:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9639:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9640: 
                   9641:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9642:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9643:      sumnewp[cptcod]=0.;
1.266     brouard  9644:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9645:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9646:    }
                   9647:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9648:   
1.266     brouard  9649:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9650:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9651:      else mobilavrange=mobilav;
                   9652:      for (age=bage; age<=fage; age++)
                   9653:        for (i=1; i<=nlstate;i++)
                   9654:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9655:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9656:      /* We keep the original values on the extreme ages bage, fage and for 
                   9657:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9658:        we use a 5 terms etc. until the borders are no more concerned. 
                   9659:      */ 
                   9660:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9661:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9662:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9663:           sumnewm[cptcod]=0.;
                   9664:           for (i=1; i<=nlstate;i++){
1.222     brouard  9665:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9666:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9667:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9668:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9669:             }
                   9670:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9671:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9672:           } /* end i */
                   9673:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9674:         } /* end cptcod */
1.222     brouard  9675:        }/* end age */
                   9676:      }/* end mob */
1.266     brouard  9677:    }else{
                   9678:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9679:      return -1;
1.266     brouard  9680:    }
                   9681: 
                   9682:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9683:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9684:      if(invalidvarcomb[cptcod]){
                   9685:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9686:        continue;
                   9687:      }
1.219     brouard  9688: 
1.266     brouard  9689:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9690:        sumnewm[cptcod]=0.;
                   9691:        sumnewmr[cptcod]=0.;
                   9692:        for (i=1; i<=nlstate;i++){
                   9693:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9694:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9695:        }
                   9696:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9697:         agemingoodr[cptcod]=age;
                   9698:        }
                   9699:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9700:           agemingood[cptcod]=age;
                   9701:        }
                   9702:      } /* age */
                   9703:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9704:        sumnewm[cptcod]=0.;
1.266     brouard  9705:        sumnewmr[cptcod]=0.;
1.222     brouard  9706:        for (i=1; i<=nlstate;i++){
                   9707:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9708:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9709:        }
                   9710:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9711:         agemaxgoodr[cptcod]=age;
1.222     brouard  9712:        }
                   9713:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9714:         agemaxgood[cptcod]=age;
                   9715:        }
                   9716:      } /* age */
                   9717:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9718:      /* but they will change */
1.288     brouard  9719:      firstA1=0;firstA2=0;
1.266     brouard  9720:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9721:        sumnewm[cptcod]=0.;
                   9722:        sumnewmr[cptcod]=0.;
                   9723:        for (i=1; i<=nlstate;i++){
                   9724:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9725:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9726:        }
                   9727:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9728:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9729:           agemaxgoodr[cptcod]=age;  /* age min */
                   9730:           for (i=1; i<=nlstate;i++)
                   9731:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9732:         }else{ /* bad we change the value with the values of good ages */
                   9733:           for (i=1; i<=nlstate;i++){
                   9734:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9735:           } /* i */
                   9736:         } /* end bad */
                   9737:        }else{
                   9738:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9739:           agemaxgood[cptcod]=age;
                   9740:         }else{ /* bad we change the value with the values of good ages */
                   9741:           for (i=1; i<=nlstate;i++){
                   9742:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9743:           } /* i */
                   9744:         } /* end bad */
                   9745:        }/* end else */
                   9746:        sum=0.;sumr=0.;
                   9747:        for (i=1; i<=nlstate;i++){
                   9748:         sum+=mobaverage[(int)age][i][cptcod];
                   9749:         sumr+=probs[(int)age][i][cptcod];
                   9750:        }
                   9751:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9752:         if(!firstA1){
                   9753:           firstA1=1;
                   9754:           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);
                   9755:         }
                   9756:         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  9757:        } /* end bad */
                   9758:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9759:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9760:         if(!firstA2){
                   9761:           firstA2=1;
                   9762:           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);
                   9763:         }
                   9764:         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  9765:        } /* end bad */
                   9766:      }/* age */
1.266     brouard  9767: 
                   9768:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9769:        sumnewm[cptcod]=0.;
1.266     brouard  9770:        sumnewmr[cptcod]=0.;
1.222     brouard  9771:        for (i=1; i<=nlstate;i++){
                   9772:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9773:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9774:        } 
                   9775:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9776:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9777:           agemingoodr[cptcod]=age;
                   9778:           for (i=1; i<=nlstate;i++)
                   9779:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9780:         }else{ /* bad we change the value with the values of good ages */
                   9781:           for (i=1; i<=nlstate;i++){
                   9782:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9783:           } /* i */
                   9784:         } /* end bad */
                   9785:        }else{
                   9786:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9787:           agemingood[cptcod]=age;
                   9788:         }else{ /* bad */
                   9789:           for (i=1; i<=nlstate;i++){
                   9790:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9791:           } /* i */
                   9792:         } /* end bad */
                   9793:        }/* end else */
                   9794:        sum=0.;sumr=0.;
                   9795:        for (i=1; i<=nlstate;i++){
                   9796:         sum+=mobaverage[(int)age][i][cptcod];
                   9797:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9798:        }
1.266     brouard  9799:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9800:         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  9801:        } /* end bad */
                   9802:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9803:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9804:         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  9805:        } /* end bad */
                   9806:      }/* age */
1.266     brouard  9807: 
1.222     brouard  9808:                
                   9809:      for (age=bage; age<=fage; age++){
1.235     brouard  9810:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9811:        sumnewp[cptcod]=0.;
                   9812:        sumnewm[cptcod]=0.;
                   9813:        for (i=1; i<=nlstate;i++){
                   9814:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9815:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9816:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9817:        }
                   9818:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9819:      }
                   9820:      /* printf("\n"); */
                   9821:      /* } */
1.266     brouard  9822: 
1.222     brouard  9823:      /* brutal averaging */
1.266     brouard  9824:      /* for (i=1; i<=nlstate;i++){ */
                   9825:      /*   for (age=1; age<=bage; age++){ */
                   9826:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9827:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9828:      /*   }     */
                   9829:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9830:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9831:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9832:      /*   } */
                   9833:      /* } /\* end i status *\/ */
                   9834:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9835:      /*   for (age=1; age<=AGESUP; age++){ */
                   9836:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9837:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9838:      /*   } */
                   9839:      /* } */
1.222     brouard  9840:    }/* end cptcod */
1.266     brouard  9841:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9842:    free_vector(agemaxgood,1, ncovcombmax);
                   9843:    free_vector(agemingood,1, ncovcombmax);
                   9844:    free_vector(agemingoodr,1, ncovcombmax);
                   9845:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9846:    free_vector(sumnewm,1, ncovcombmax);
                   9847:    free_vector(sumnewp,1, ncovcombmax);
                   9848:    return 0;
                   9849:  }/* End movingaverage */
1.218     brouard  9850:  
1.126     brouard  9851: 
1.296     brouard  9852:  
1.126     brouard  9853: /************** Forecasting ******************/
1.296     brouard  9854: /* 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)*/
                   9855: 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){
                   9856:   /* dateintemean, mean date of interviews
                   9857:      dateprojd, year, month, day of starting projection 
                   9858:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9859:      agemin, agemax range of age
                   9860:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9861:   */
1.296     brouard  9862:   /* double anprojd, mprojd, jprojd; */
                   9863:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9864:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9865:   double agec; /* generic age */
1.296     brouard  9866:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9867:   double *popeffectif,*popcount;
                   9868:   double ***p3mat;
1.218     brouard  9869:   /* double ***mobaverage; */
1.126     brouard  9870:   char fileresf[FILENAMELENGTH];
                   9871: 
                   9872:   agelim=AGESUP;
1.211     brouard  9873:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9874:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9875:      We still use firstpass and lastpass as another selection.
                   9876:   */
1.214     brouard  9877:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9878:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9879:  
1.201     brouard  9880:   strcpy(fileresf,"F_"); 
                   9881:   strcat(fileresf,fileresu);
1.126     brouard  9882:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9883:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9884:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9885:   }
1.235     brouard  9886:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9887:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9888: 
1.225     brouard  9889:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9890: 
                   9891: 
                   9892:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9893:   if (stepm<=12) stepsize=1;
                   9894:   if(estepm < stepm){
                   9895:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9896:   }
1.270     brouard  9897:   else{
                   9898:     hstepm=estepm;   
                   9899:   }
                   9900:   if(estepm > stepm){ /* Yes every two year */
                   9901:     stepsize=2;
                   9902:   }
1.296     brouard  9903:   hstepm=hstepm/stepm;
1.126     brouard  9904: 
1.296     brouard  9905:   
                   9906:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9907:   /*                              fractional in yp1 *\/ */
                   9908:   /* aintmean=yp; */
                   9909:   /* yp2=modf((yp1*12),&yp); */
                   9910:   /* mintmean=yp; */
                   9911:   /* yp1=modf((yp2*30.5),&yp); */
                   9912:   /* jintmean=yp; */
                   9913:   /* if(jintmean==0) jintmean=1; */
                   9914:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9915: 
1.296     brouard  9916: 
                   9917:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9918:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9919:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9920:   i1=pow(2,cptcoveff);
1.126     brouard  9921:   if (cptcovn < 1){i1=1;}
                   9922:   
1.296     brouard  9923:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9924:   
                   9925:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9926:   
1.126     brouard  9927: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9928:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9929:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9930:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9931:       continue;
1.227     brouard  9932:     if(invalidvarcomb[k]){
                   9933:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9934:       continue;
                   9935:     }
                   9936:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9937:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9938:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9939:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9940:     }
1.235     brouard  9941:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9942:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9943:     }
1.227     brouard  9944:     fprintf(ficresf," yearproj age");
                   9945:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9946:       for(i=1; i<=nlstate;i++)               
                   9947:        fprintf(ficresf," p%d%d",i,j);
                   9948:       fprintf(ficresf," wp.%d",j);
                   9949:     }
1.296     brouard  9950:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9951:       fprintf(ficresf,"\n");
1.296     brouard  9952:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9953:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9954:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9955:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9956:        nhstepm = nhstepm/hstepm; 
                   9957:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9958:        oldm=oldms;savm=savms;
1.268     brouard  9959:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9960:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9961:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9962:        for (h=0; h<=nhstepm; h++){
                   9963:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9964:            break;
                   9965:          }
                   9966:        }
                   9967:        fprintf(ficresf,"\n");
                   9968:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9969:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9970:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9971:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9972:        
                   9973:        for(j=1; j<=nlstate+ndeath;j++) {
                   9974:          ppij=0.;
                   9975:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9976:            if (mobilav>=1)
                   9977:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9978:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9979:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9980:            }
1.268     brouard  9981:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9982:          } /* end i */
                   9983:          fprintf(ficresf," %.3f", ppij);
                   9984:        }/* end j */
1.227     brouard  9985:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9986:       } /* end agec */
1.266     brouard  9987:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9988:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9989:     } /* end yearp */
                   9990:   } /* end  k */
1.219     brouard  9991:        
1.126     brouard  9992:   fclose(ficresf);
1.215     brouard  9993:   printf("End of Computing forecasting \n");
                   9994:   fprintf(ficlog,"End of Computing forecasting\n");
                   9995: 
1.126     brouard  9996: }
                   9997: 
1.269     brouard  9998: /************** Back Forecasting ******************/
1.296     brouard  9999:  /* 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){ */
                   10000:  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){
                   10001:   /* back1, year, month, day of starting backprojection
1.267     brouard  10002:      agemin, agemax range of age
                   10003:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10004:      anback2 year of end of backprojection (same day and month as back1).
                   10005:      prevacurrent and prev are prevalences.
1.267     brouard  10006:   */
                   10007:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10008:   double agec; /* generic age */
1.302     brouard  10009:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10010:   double *popeffectif,*popcount;
                   10011:   double ***p3mat;
                   10012:   /* double ***mobaverage; */
                   10013:   char fileresfb[FILENAMELENGTH];
                   10014:  
1.268     brouard  10015:   agelim=AGEINF;
1.267     brouard  10016:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10017:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10018:      We still use firstpass and lastpass as another selection.
                   10019:   */
                   10020:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10021:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10022: 
                   10023:   /*Do we need to compute prevalence again?*/
                   10024: 
                   10025:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10026:   
                   10027:   strcpy(fileresfb,"FB_");
                   10028:   strcat(fileresfb,fileresu);
                   10029:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10030:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10031:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10032:   }
                   10033:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10034:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10035:   
                   10036:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10037:   
                   10038:    
                   10039:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10040:   if (stepm<=12) stepsize=1;
                   10041:   if(estepm < stepm){
                   10042:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10043:   }
1.270     brouard  10044:   else{
                   10045:     hstepm=estepm;   
                   10046:   }
                   10047:   if(estepm >= stepm){ /* Yes every two year */
                   10048:     stepsize=2;
                   10049:   }
1.267     brouard  10050:   
                   10051:   hstepm=hstepm/stepm;
1.296     brouard  10052:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10053:   /*                              fractional in yp1 *\/ */
                   10054:   /* aintmean=yp; */
                   10055:   /* yp2=modf((yp1*12),&yp); */
                   10056:   /* mintmean=yp; */
                   10057:   /* yp1=modf((yp2*30.5),&yp); */
                   10058:   /* jintmean=yp; */
                   10059:   /* if(jintmean==0) jintmean=1; */
                   10060:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10061:   
                   10062:   i1=pow(2,cptcoveff);
                   10063:   if (cptcovn < 1){i1=1;}
                   10064:   
1.296     brouard  10065:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10066:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10067:   
                   10068:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10069:   
                   10070:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   10071:   for(k=1; k<=i1;k++){
                   10072:     if(i1 != 1 && TKresult[nres]!= k)
                   10073:       continue;
                   10074:     if(invalidvarcomb[k]){
                   10075:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   10076:       continue;
                   10077:     }
1.268     brouard  10078:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  10079:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  10080:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  10081:     }
                   10082:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   10083:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   10084:     }
                   10085:     fprintf(ficresfb," yearbproj age");
                   10086:     for(j=1; j<=nlstate+ndeath;j++){
                   10087:       for(i=1; i<=nlstate;i++)
1.268     brouard  10088:        fprintf(ficresfb," b%d%d",i,j);
                   10089:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10090:     }
1.296     brouard  10091:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10092:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10093:       fprintf(ficresfb,"\n");
1.296     brouard  10094:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10095:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10096:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10097:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10098:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10099:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10100:        nhstepm = nhstepm/hstepm;
                   10101:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10102:        oldm=oldms;savm=savms;
1.268     brouard  10103:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10104:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10105:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10106:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10107:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10108:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10109:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10110:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10111:            break;
                   10112:          }
                   10113:        }
                   10114:        fprintf(ficresfb,"\n");
                   10115:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  10116:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  10117:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10118:        for(i=1; i<=nlstate+ndeath;i++) {
                   10119:          ppij=0.;ppi=0.;
                   10120:          for(j=1; j<=nlstate;j++) {
                   10121:            /* if (mobilav==1) */
1.269     brouard  10122:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10123:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10124:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10125:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10126:              /* else { */
                   10127:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10128:              /* } */
1.268     brouard  10129:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10130:          } /* end j */
                   10131:          if(ppi <0.99){
                   10132:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10133:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10134:          }
                   10135:          fprintf(ficresfb," %.3f", ppij);
                   10136:        }/* end j */
1.267     brouard  10137:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10138:       } /* end agec */
                   10139:     } /* end yearp */
                   10140:   } /* end k */
1.217     brouard  10141:   
1.267     brouard  10142:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10143:   
1.267     brouard  10144:   fclose(ficresfb);
                   10145:   printf("End of Computing Back forecasting \n");
                   10146:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10147:        
1.267     brouard  10148: }
1.217     brouard  10149: 
1.269     brouard  10150: /* Variance of prevalence limit: varprlim */
                   10151:  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  10152:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10153:  
                   10154:    char fileresvpl[FILENAMELENGTH];  
                   10155:    FILE *ficresvpl;
                   10156:    double **oldm, **savm;
                   10157:    double **varpl; /* Variances of prevalence limits by age */   
                   10158:    int i1, k, nres, j ;
                   10159:    
                   10160:     strcpy(fileresvpl,"VPL_");
                   10161:     strcat(fileresvpl,fileresu);
                   10162:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10163:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10164:       exit(0);
                   10165:     }
1.288     brouard  10166:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10167:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10168:     
                   10169:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10170:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10171:     
                   10172:     i1=pow(2,cptcoveff);
                   10173:     if (cptcovn < 1){i1=1;}
                   10174: 
1.337     brouard  10175:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10176:        k=TKresult[nres];
1.338     brouard  10177:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10178:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10179:       if(i1 != 1 && TKresult[nres]!= k)
                   10180:        continue;
                   10181:       fprintf(ficresvpl,"\n#****** ");
                   10182:       printf("\n#****** ");
                   10183:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10184:       for(j=1;j<=cptcovs;j++) {
                   10185:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10186:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10187:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10188:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10189:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10190:       }
1.337     brouard  10191:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10192:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10193:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10194:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10195:       /* }      */
1.269     brouard  10196:       fprintf(ficresvpl,"******\n");
                   10197:       printf("******\n");
                   10198:       fprintf(ficlog,"******\n");
                   10199:       
                   10200:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10201:       oldm=oldms;savm=savms;
                   10202:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10203:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10204:       /*}*/
                   10205:     }
                   10206:     
                   10207:     fclose(ficresvpl);
1.288     brouard  10208:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10209:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10210: 
                   10211:  }
                   10212: /* Variance of back prevalence: varbprlim */
                   10213:  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){
                   10214:       /*------- Variance of back (stable) prevalence------*/
                   10215: 
                   10216:    char fileresvbl[FILENAMELENGTH];  
                   10217:    FILE  *ficresvbl;
                   10218: 
                   10219:    double **oldm, **savm;
                   10220:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10221:    int i1, k, nres, j ;
                   10222: 
                   10223:    strcpy(fileresvbl,"VBL_");
                   10224:    strcat(fileresvbl,fileresu);
                   10225:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10226:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10227:      exit(0);
                   10228:    }
                   10229:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10230:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10231:    
                   10232:    
                   10233:    i1=pow(2,cptcoveff);
                   10234:    if (cptcovn < 1){i1=1;}
                   10235:    
1.337     brouard  10236:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10237:      k=TKresult[nres];
1.338     brouard  10238:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10239:     /* for(k=1; k<=i1;k++){ */
                   10240:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10241:     /*          continue; */
1.269     brouard  10242:        fprintf(ficresvbl,"\n#****** ");
                   10243:        printf("\n#****** ");
                   10244:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10245:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10246:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10247:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10248:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10249:        /* for(j=1;j<=cptcoveff;j++) { */
                   10250:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10251:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10252:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10253:        /* } */
                   10254:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10255:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10256:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10257:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10258:        }
                   10259:        fprintf(ficresvbl,"******\n");
                   10260:        printf("******\n");
                   10261:        fprintf(ficlog,"******\n");
                   10262:        
                   10263:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10264:        oldm=oldms;savm=savms;
                   10265:        
                   10266:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10267:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10268:        /*}*/
                   10269:      }
                   10270:    
                   10271:    fclose(ficresvbl);
                   10272:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10273:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10274: 
                   10275:  } /* End of varbprlim */
                   10276: 
1.126     brouard  10277: /************** Forecasting *****not tested NB*************/
1.227     brouard  10278: /* 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  10279:   
1.227     brouard  10280: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10281: /*   int *popage; */
                   10282: /*   double calagedatem, agelim, kk1, kk2; */
                   10283: /*   double *popeffectif,*popcount; */
                   10284: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10285: /*   /\* double ***mobaverage; *\/ */
                   10286: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10287: 
1.227     brouard  10288: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10289: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10290: /*   agelim=AGESUP; */
                   10291: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10292:   
1.227     brouard  10293: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10294:   
                   10295:   
1.227     brouard  10296: /*   strcpy(filerespop,"POP_");  */
                   10297: /*   strcat(filerespop,fileresu); */
                   10298: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10299: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10300: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10301: /*   } */
                   10302: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10303: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10304: 
1.227     brouard  10305: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10306: 
1.227     brouard  10307: /*   /\* if (mobilav!=0) { *\/ */
                   10308: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10309: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10310: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10311: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10312: /*   /\*   } *\/ */
                   10313: /*   /\* } *\/ */
1.126     brouard  10314: 
1.227     brouard  10315: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10316: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10317:   
1.227     brouard  10318: /*   agelim=AGESUP; */
1.126     brouard  10319:   
1.227     brouard  10320: /*   hstepm=1; */
                   10321: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10322:        
1.227     brouard  10323: /*   if (popforecast==1) { */
                   10324: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10325: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10326: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10327: /*     }  */
                   10328: /*     popage=ivector(0,AGESUP); */
                   10329: /*     popeffectif=vector(0,AGESUP); */
                   10330: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10331:     
1.227     brouard  10332: /*     i=1;    */
                   10333: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10334:     
1.227     brouard  10335: /*     imx=i; */
                   10336: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10337: /*   } */
1.218     brouard  10338:   
1.227     brouard  10339: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10340: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10341: /*       k=k+1; */
                   10342: /*       fprintf(ficrespop,"\n#******"); */
                   10343: /*       for(j=1;j<=cptcoveff;j++) { */
                   10344: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10345: /*       } */
                   10346: /*       fprintf(ficrespop,"******\n"); */
                   10347: /*       fprintf(ficrespop,"# Age"); */
                   10348: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10349: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10350:       
1.227     brouard  10351: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10352: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10353:        
1.227     brouard  10354: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10355: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10356: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10357:          
1.227     brouard  10358: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10359: /*       oldm=oldms;savm=savms; */
                   10360: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10361:          
1.227     brouard  10362: /*       for (h=0; h<=nhstepm; h++){ */
                   10363: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10364: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10365: /*         }  */
                   10366: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10367: /*           kk1=0.;kk2=0; */
                   10368: /*           for(i=1; i<=nlstate;i++) {               */
                   10369: /*             if (mobilav==1)  */
                   10370: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10371: /*             else { */
                   10372: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10373: /*             } */
                   10374: /*           } */
                   10375: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10376: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10377: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10378: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10379: /*           } */
                   10380: /*         } */
                   10381: /*         for(i=1; i<=nlstate;i++){ */
                   10382: /*           kk1=0.; */
                   10383: /*           for(j=1; j<=nlstate;j++){ */
                   10384: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10385: /*           } */
                   10386: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10387: /*         } */
1.218     brouard  10388:            
1.227     brouard  10389: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10390: /*           for(j=1; j<=nlstate;j++)  */
                   10391: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10392: /*       } */
                   10393: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10394: /*     } */
                   10395: /*       } */
1.218     brouard  10396:       
1.227     brouard  10397: /*       /\******\/ */
1.218     brouard  10398:       
1.227     brouard  10399: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10400: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10401: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10402: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10403: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10404:          
1.227     brouard  10405: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10406: /*       oldm=oldms;savm=savms; */
                   10407: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10408: /*       for (h=0; h<=nhstepm; h++){ */
                   10409: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10410: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10411: /*         }  */
                   10412: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10413: /*           kk1=0.;kk2=0; */
                   10414: /*           for(i=1; i<=nlstate;i++) {               */
                   10415: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10416: /*           } */
                   10417: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10418: /*         } */
                   10419: /*       } */
                   10420: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10421: /*     } */
                   10422: /*       } */
                   10423: /*     }  */
                   10424: /*   } */
1.218     brouard  10425:   
1.227     brouard  10426: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10427:   
1.227     brouard  10428: /*   if (popforecast==1) { */
                   10429: /*     free_ivector(popage,0,AGESUP); */
                   10430: /*     free_vector(popeffectif,0,AGESUP); */
                   10431: /*     free_vector(popcount,0,AGESUP); */
                   10432: /*   } */
                   10433: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10434: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10435: /*   fclose(ficrespop); */
                   10436: /* } /\* End of popforecast *\/ */
1.218     brouard  10437:  
1.126     brouard  10438: int fileappend(FILE *fichier, char *optionfich)
                   10439: {
                   10440:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10441:     printf("Problem with file: %s\n", optionfich);
                   10442:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10443:     return (0);
                   10444:   }
                   10445:   fflush(fichier);
                   10446:   return (1);
                   10447: }
                   10448: 
                   10449: 
                   10450: /**************** function prwizard **********************/
                   10451: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10452: {
                   10453: 
                   10454:   /* Wizard to print covariance matrix template */
                   10455: 
1.164     brouard  10456:   char ca[32], cb[32];
                   10457:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10458:   int numlinepar;
                   10459: 
                   10460:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10461:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10462:   for(i=1; i <=nlstate; i++){
                   10463:     jj=0;
                   10464:     for(j=1; j <=nlstate+ndeath; j++){
                   10465:       if(j==i) continue;
                   10466:       jj++;
                   10467:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10468:       printf("%1d%1d",i,j);
                   10469:       fprintf(ficparo,"%1d%1d",i,j);
                   10470:       for(k=1; k<=ncovmodel;k++){
                   10471:        /*        printf(" %lf",param[i][j][k]); */
                   10472:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10473:        printf(" 0.");
                   10474:        fprintf(ficparo," 0.");
                   10475:       }
                   10476:       printf("\n");
                   10477:       fprintf(ficparo,"\n");
                   10478:     }
                   10479:   }
                   10480:   printf("# Scales (for hessian or gradient estimation)\n");
                   10481:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10482:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10483:   for(i=1; i <=nlstate; i++){
                   10484:     jj=0;
                   10485:     for(j=1; j <=nlstate+ndeath; j++){
                   10486:       if(j==i) continue;
                   10487:       jj++;
                   10488:       fprintf(ficparo,"%1d%1d",i,j);
                   10489:       printf("%1d%1d",i,j);
                   10490:       fflush(stdout);
                   10491:       for(k=1; k<=ncovmodel;k++){
                   10492:        /*      printf(" %le",delti3[i][j][k]); */
                   10493:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10494:        printf(" 0.");
                   10495:        fprintf(ficparo," 0.");
                   10496:       }
                   10497:       numlinepar++;
                   10498:       printf("\n");
                   10499:       fprintf(ficparo,"\n");
                   10500:     }
                   10501:   }
                   10502:   printf("# Covariance matrix\n");
                   10503: /* # 121 Var(a12)\n\ */
                   10504: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10505: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10506: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10507: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10508: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10509: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10510: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10511:   fflush(stdout);
                   10512:   fprintf(ficparo,"# Covariance matrix\n");
                   10513:   /* # 121 Var(a12)\n\ */
                   10514:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10515:   /* #   ...\n\ */
                   10516:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10517:   
                   10518:   for(itimes=1;itimes<=2;itimes++){
                   10519:     jj=0;
                   10520:     for(i=1; i <=nlstate; i++){
                   10521:       for(j=1; j <=nlstate+ndeath; j++){
                   10522:        if(j==i) continue;
                   10523:        for(k=1; k<=ncovmodel;k++){
                   10524:          jj++;
                   10525:          ca[0]= k+'a'-1;ca[1]='\0';
                   10526:          if(itimes==1){
                   10527:            printf("#%1d%1d%d",i,j,k);
                   10528:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10529:          }else{
                   10530:            printf("%1d%1d%d",i,j,k);
                   10531:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10532:            /*  printf(" %.5le",matcov[i][j]); */
                   10533:          }
                   10534:          ll=0;
                   10535:          for(li=1;li <=nlstate; li++){
                   10536:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10537:              if(lj==li) continue;
                   10538:              for(lk=1;lk<=ncovmodel;lk++){
                   10539:                ll++;
                   10540:                if(ll<=jj){
                   10541:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10542:                  if(ll<jj){
                   10543:                    if(itimes==1){
                   10544:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10545:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10546:                    }else{
                   10547:                      printf(" 0.");
                   10548:                      fprintf(ficparo," 0.");
                   10549:                    }
                   10550:                  }else{
                   10551:                    if(itimes==1){
                   10552:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10553:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10554:                    }else{
                   10555:                      printf(" 0.");
                   10556:                      fprintf(ficparo," 0.");
                   10557:                    }
                   10558:                  }
                   10559:                }
                   10560:              } /* end lk */
                   10561:            } /* end lj */
                   10562:          } /* end li */
                   10563:          printf("\n");
                   10564:          fprintf(ficparo,"\n");
                   10565:          numlinepar++;
                   10566:        } /* end k*/
                   10567:       } /*end j */
                   10568:     } /* end i */
                   10569:   } /* end itimes */
                   10570: 
                   10571: } /* end of prwizard */
                   10572: /******************* Gompertz Likelihood ******************************/
                   10573: double gompertz(double x[])
                   10574: { 
1.302     brouard  10575:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10576:   int i,n=0; /* n is the size of the sample */
                   10577: 
1.220     brouard  10578:   for (i=1;i<=imx ; i++) {
1.126     brouard  10579:     sump=sump+weight[i];
                   10580:     /*    sump=sump+1;*/
                   10581:     num=num+1;
                   10582:   }
1.302     brouard  10583:   L=0.0;
                   10584:   /* agegomp=AGEGOMP; */
1.126     brouard  10585:   /* for (i=0; i<=imx; i++) 
                   10586:      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]);*/
                   10587: 
1.302     brouard  10588:   for (i=1;i<=imx ; i++) {
                   10589:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10590:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10591:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10592:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10593:      * +
                   10594:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10595:      */
                   10596:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10597:        if (cens[i] == 1){
                   10598:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10599:        } else if (cens[i] == 0){
1.126     brouard  10600:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10601:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10602:       } else
                   10603:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10604:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10605:        L=L+A*weight[i];
1.126     brouard  10606:        /*      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  10607:      }
                   10608:   }
1.126     brouard  10609: 
1.302     brouard  10610:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10611:  
                   10612:   return -2*L*num/sump;
                   10613: }
                   10614: 
1.136     brouard  10615: #ifdef GSL
                   10616: /******************* Gompertz_f Likelihood ******************************/
                   10617: double gompertz_f(const gsl_vector *v, void *params)
                   10618: { 
1.302     brouard  10619:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10620:   double *x= (double *) v->data;
                   10621:   int i,n=0; /* n is the size of the sample */
                   10622: 
                   10623:   for (i=0;i<=imx-1 ; i++) {
                   10624:     sump=sump+weight[i];
                   10625:     /*    sump=sump+1;*/
                   10626:     num=num+1;
                   10627:   }
                   10628:  
                   10629:  
                   10630:   /* for (i=0; i<=imx; i++) 
                   10631:      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]);*/
                   10632:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10633:   for (i=1;i<=imx ; i++)
                   10634:     {
                   10635:       if (cens[i] == 1 && wav[i]>1)
                   10636:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10637:       
                   10638:       if (cens[i] == 0 && wav[i]>1)
                   10639:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10640:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10641:       
                   10642:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10643:       if (wav[i] > 1 ) { /* ??? */
                   10644:        LL=LL+A*weight[i];
                   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]);*/
                   10646:       }
                   10647:     }
                   10648: 
                   10649:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10650:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10651:  
                   10652:   return -2*LL*num/sump;
                   10653: }
                   10654: #endif
                   10655: 
1.126     brouard  10656: /******************* Printing html file ***********/
1.201     brouard  10657: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10658:                  int lastpass, int stepm, int weightopt, char model[],\
                   10659:                  int imx,  double p[],double **matcov,double agemortsup){
                   10660:   int i,k;
                   10661: 
                   10662:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10663:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10664:   for (i=1;i<=2;i++) 
                   10665:     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  10666:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10667:   fprintf(fichtm,"</ul>");
                   10668: 
                   10669: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10670: 
                   10671:  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>");
                   10672: 
                   10673:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10674:    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]);
                   10675: 
                   10676:  
                   10677:   fflush(fichtm);
                   10678: }
                   10679: 
                   10680: /******************* Gnuplot file **************/
1.201     brouard  10681: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10682: 
                   10683:   char dirfileres[132],optfileres[132];
1.164     brouard  10684: 
1.126     brouard  10685:   int ng;
                   10686: 
                   10687: 
                   10688:   /*#ifdef windows */
                   10689:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10690:     /*#endif */
                   10691: 
                   10692: 
                   10693:   strcpy(dirfileres,optionfilefiname);
                   10694:   strcpy(optfileres,"vpl");
1.199     brouard  10695:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10696:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10697:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10698:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10699:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10700: 
                   10701: } 
                   10702: 
1.136     brouard  10703: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10704: {
1.126     brouard  10705: 
1.136     brouard  10706:   /*-------- data file ----------*/
                   10707:   FILE *fic;
                   10708:   char dummy[]="                         ";
1.240     brouard  10709:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10710:   int lstra;
1.136     brouard  10711:   int linei, month, year,iout;
1.302     brouard  10712:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10713:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10714:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10715:   char *stratrunc;
1.223     brouard  10716: 
1.349     brouard  10717:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10718:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10719:   
                   10720:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10721:   
1.136     brouard  10722:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10723:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10724:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10725:   }
1.126     brouard  10726: 
1.302     brouard  10727:     /* Is it a BOM UTF-8 Windows file? */
                   10728:   /* First data line */
                   10729:   linei=0;
                   10730:   while(fgets(line, MAXLINE, fic)) {
                   10731:     noffset=0;
                   10732:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10733:     {
                   10734:       noffset=noffset+3;
                   10735:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10736:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10737:       fflush(ficlog); return 1;
                   10738:     }
                   10739:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10740:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10741:     {
                   10742:       noffset=noffset+2;
1.304     brouard  10743:       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);
                   10744:       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  10745:       fflush(ficlog); return 1;
                   10746:     }
                   10747:     else if( line[0] == 0 && line[1] == 0)
                   10748:     {
                   10749:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10750:        noffset=noffset+4;
1.304     brouard  10751:        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);
                   10752:        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  10753:        fflush(ficlog); return 1;
                   10754:       }
                   10755:     } else{
                   10756:       ;/*printf(" Not a BOM file\n");*/
                   10757:     }
                   10758:         /* If line starts with a # it is a comment */
                   10759:     if (line[noffset] == '#') {
                   10760:       linei=linei+1;
                   10761:       break;
                   10762:     }else{
                   10763:       break;
                   10764:     }
                   10765:   }
                   10766:   fclose(fic);
                   10767:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10768:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10769:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10770:   }
                   10771:   /* Not a Bom file */
                   10772:   
1.136     brouard  10773:   i=1;
                   10774:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10775:     linei=linei+1;
                   10776:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10777:       if(line[j] == '\t')
                   10778:        line[j] = ' ';
                   10779:     }
                   10780:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10781:       ;
                   10782:     };
                   10783:     line[j+1]=0;  /* Trims blanks at end of line */
                   10784:     if(line[0]=='#'){
                   10785:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10786:       printf("Comment line\n%s\n",line);
                   10787:       continue;
                   10788:     }
                   10789:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10790:     strcpy(line, linetmp);
1.223     brouard  10791:     
                   10792:     /* Loops on waves */
                   10793:     for (j=maxwav;j>=1;j--){
                   10794:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10795:        cutv(stra, strb, line, ' '); 
                   10796:        if(strb[0]=='.') { /* Missing value */
                   10797:          lval=-1;
                   10798:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10799:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10800:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10801:            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);
                   10802:            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);
                   10803:            return 1;
                   10804:          }
                   10805:        }else{
                   10806:          errno=0;
                   10807:          /* what_kind_of_number(strb); */
                   10808:          dval=strtod(strb,&endptr); 
                   10809:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10810:          /* if(strb != endptr && *endptr == '\0') */
                   10811:          /*    dval=dlval; */
                   10812:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10813:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10814:            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);
                   10815:            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);
                   10816:            return 1;
                   10817:          }
                   10818:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10819:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10820:        }
                   10821:        strcpy(line,stra);
1.223     brouard  10822:       }/* end loop ntqv */
1.225     brouard  10823:       
1.223     brouard  10824:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10825:        cutv(stra, strb, line, ' '); 
                   10826:        if(strb[0]=='.') { /* Missing value */
                   10827:          lval=-1;
                   10828:        }else{
                   10829:          errno=0;
                   10830:          lval=strtol(strb,&endptr,10); 
                   10831:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10832:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10833:            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);
                   10834:            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);
                   10835:            return 1;
                   10836:          }
                   10837:        }
                   10838:        if(lval <-1 || lval >1){
                   10839:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10840:  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  10841:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10842:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10843:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10844:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10845:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10846:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10847:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10848:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10849:  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  10850:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10851:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10852:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10853:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10854:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10855:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10856:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10857:          return 1;
                   10858:        }
1.341     brouard  10859:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10860:        strcpy(line,stra);
1.223     brouard  10861:       }/* end loop ntv */
1.225     brouard  10862:       
1.223     brouard  10863:       /* Statuses  at wave */
1.137     brouard  10864:       cutv(stra, strb, line, ' '); 
1.223     brouard  10865:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10866:        lval=-1;
1.136     brouard  10867:       }else{
1.238     brouard  10868:        errno=0;
                   10869:        lval=strtol(strb,&endptr,10); 
                   10870:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10871:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10872:          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);
                   10873:          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);
                   10874:          return 1;
                   10875:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10876:          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);
                   10877:          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  10878:          return 1;
                   10879:        }
1.136     brouard  10880:       }
1.225     brouard  10881:       
1.136     brouard  10882:       s[j][i]=lval;
1.225     brouard  10883:       
1.223     brouard  10884:       /* Date of Interview */
1.136     brouard  10885:       strcpy(line,stra);
                   10886:       cutv(stra, strb,line,' ');
1.169     brouard  10887:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10888:       }
1.169     brouard  10889:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10890:        month=99;
                   10891:        year=9999;
1.136     brouard  10892:       }else{
1.225     brouard  10893:        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);
                   10894:        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);
                   10895:        return 1;
1.136     brouard  10896:       }
                   10897:       anint[j][i]= (double) year; 
1.302     brouard  10898:       mint[j][i]= (double)month;
                   10899:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10900:       /*       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]); */
                   10901:       /*       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]); */
                   10902:       /* } */
1.136     brouard  10903:       strcpy(line,stra);
1.223     brouard  10904:     } /* End loop on waves */
1.225     brouard  10905:     
1.223     brouard  10906:     /* Date of death */
1.136     brouard  10907:     cutv(stra, strb,line,' '); 
1.169     brouard  10908:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10909:     }
1.169     brouard  10910:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10911:       month=99;
                   10912:       year=9999;
                   10913:     }else{
1.141     brouard  10914:       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  10915:       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);
                   10916:       return 1;
1.136     brouard  10917:     }
                   10918:     andc[i]=(double) year; 
                   10919:     moisdc[i]=(double) month; 
                   10920:     strcpy(line,stra);
                   10921:     
1.223     brouard  10922:     /* Date of birth */
1.136     brouard  10923:     cutv(stra, strb,line,' '); 
1.169     brouard  10924:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10925:     }
1.169     brouard  10926:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10927:       month=99;
                   10928:       year=9999;
                   10929:     }else{
1.141     brouard  10930:       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);
                   10931:       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  10932:       return 1;
1.136     brouard  10933:     }
                   10934:     if (year==9999) {
1.141     brouard  10935:       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);
                   10936:       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  10937:       return 1;
                   10938:       
1.136     brouard  10939:     }
                   10940:     annais[i]=(double)(year);
1.302     brouard  10941:     moisnais[i]=(double)(month);
                   10942:     for (j=1;j<=maxwav;j++){
                   10943:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10944:        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]);
                   10945:        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]);
                   10946:       }
                   10947:     }
                   10948: 
1.136     brouard  10949:     strcpy(line,stra);
1.225     brouard  10950:     
1.223     brouard  10951:     /* Sample weight */
1.136     brouard  10952:     cutv(stra, strb,line,' '); 
                   10953:     errno=0;
                   10954:     dval=strtod(strb,&endptr); 
                   10955:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10956:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10957:       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  10958:       fflush(ficlog);
                   10959:       return 1;
                   10960:     }
                   10961:     weight[i]=dval; 
                   10962:     strcpy(line,stra);
1.225     brouard  10963:     
1.223     brouard  10964:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10965:       cutv(stra, strb, line, ' '); 
                   10966:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10967:        lval=-1;
1.311     brouard  10968:        coqvar[iv][i]=NAN; 
                   10969:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10970:       }else{
1.225     brouard  10971:        errno=0;
                   10972:        /* what_kind_of_number(strb); */
                   10973:        dval=strtod(strb,&endptr);
                   10974:        /* if(strb != endptr && *endptr == '\0') */
                   10975:        /*   dval=dlval; */
                   10976:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10977:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10978:          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);
                   10979:          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);
                   10980:          return 1;
                   10981:        }
                   10982:        coqvar[iv][i]=dval; 
1.226     brouard  10983:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10984:       }
                   10985:       strcpy(line,stra);
                   10986:     }/* end loop nqv */
1.136     brouard  10987:     
1.223     brouard  10988:     /* Covariate values */
1.136     brouard  10989:     for (j=ncovcol;j>=1;j--){
                   10990:       cutv(stra, strb,line,' '); 
1.223     brouard  10991:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10992:        lval=-1;
1.136     brouard  10993:       }else{
1.225     brouard  10994:        errno=0;
                   10995:        lval=strtol(strb,&endptr,10); 
                   10996:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10997:          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);
                   10998:          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);
                   10999:          return 1;
                   11000:        }
1.136     brouard  11001:       }
                   11002:       if(lval <-1 || lval >1){
1.225     brouard  11003:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11004:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11005:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11006:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11007:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11008:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11009:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11010:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11011:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11012:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11013:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11014:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11015:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11016:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11017:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11018:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11019:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11020:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11021:        return 1;
1.136     brouard  11022:       }
                   11023:       covar[j][i]=(double)(lval);
                   11024:       strcpy(line,stra);
                   11025:     }  
                   11026:     lstra=strlen(stra);
1.225     brouard  11027:     
1.136     brouard  11028:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11029:       stratrunc = &(stra[lstra-9]);
                   11030:       num[i]=atol(stratrunc);
                   11031:     }
                   11032:     else
                   11033:       num[i]=atol(stra);
                   11034:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11035:       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;}*/
                   11036:     
                   11037:     i=i+1;
                   11038:   } /* End loop reading  data */
1.225     brouard  11039:   
1.136     brouard  11040:   *imax=i-1; /* Number of individuals */
                   11041:   fclose(fic);
1.225     brouard  11042:   
1.136     brouard  11043:   return (0);
1.164     brouard  11044:   /* endread: */
1.225     brouard  11045:   printf("Exiting readdata: ");
                   11046:   fclose(fic);
                   11047:   return (1);
1.223     brouard  11048: }
1.126     brouard  11049: 
1.234     brouard  11050: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11051:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11052:   while (*p2 == ' ')
1.234     brouard  11053:     p2++; 
                   11054:   /* while ((*p1++ = *p2++) !=0) */
                   11055:   /*   ; */
                   11056:   /* do */
                   11057:   /*   while (*p2 == ' ') */
                   11058:   /*     p2++; */
                   11059:   /* while (*p1++ == *p2++); */
                   11060:   *stri=p2; 
1.145     brouard  11061: }
                   11062: 
1.330     brouard  11063: int decoderesult( char resultline[], int nres)
1.230     brouard  11064: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11065: {
1.235     brouard  11066:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11067:   char resultsav[MAXLINE];
1.330     brouard  11068:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11069:   /* int modelresult[MAXLINE]; */
1.230     brouard  11070:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11071: 
1.234     brouard  11072:   removefirstspace(&resultline);
1.332     brouard  11073:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11074: 
1.332     brouard  11075:   strcpy(resultsav,resultline);
1.342     brouard  11076:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11077:   if (strlen(resultsav) >1){
1.334     brouard  11078:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11079:   }
1.253     brouard  11080:   if(j == 0){ /* Resultline but no = */
                   11081:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11082:     return (0);
                   11083:   }
1.234     brouard  11084:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  11085:     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);
                   11086:     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  11087:     /* return 1;*/
1.234     brouard  11088:   }
1.334     brouard  11089:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11090:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11091:       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  11092:       /* 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  11093:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11094:       /* If a blank, then strc="V4=" and strd='\0' */
                   11095:       if(strc[0]=='\0'){
                   11096:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11097:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11098:        return 1;
                   11099:       }
1.234     brouard  11100:     }else
                   11101:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11102:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11103:     
1.230     brouard  11104:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11105:     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  11106:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11107:     /* cptcovsel++;     */
                   11108:     if (nbocc(stra,'=') >0)
                   11109:       strcpy(resultsav,stra); /* and analyzes it */
                   11110:   }
1.235     brouard  11111:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11112:   /* 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  11113:   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  11114:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11115:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11116:       match=0;
1.318     brouard  11117:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11118:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11119:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11120:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11121:          break;
                   11122:        }
                   11123:       }
                   11124:       if(match == 0){
1.338     brouard  11125:        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]);
                   11126:        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  11127:        return 1;
1.234     brouard  11128:       }
1.332     brouard  11129:     }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*/
                   11130:       /* We feed resultmodel[k1]=k2; */
                   11131:       match=0;
                   11132:       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 */
                   11133:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11134:          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  11135:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11136:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11137:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11138:          break;
                   11139:        }
                   11140:       }
                   11141:       if(match == 0){
1.338     brouard  11142:        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]);
                   11143:        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  11144:       return 1;
                   11145:       }
1.349     brouard  11146:     }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  11147:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11148:       match=0;
1.342     brouard  11149:       /* 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  11150:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11151:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11152:          /* modelresult[k2]=k1; */
1.342     brouard  11153:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11154:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11155:        }
                   11156:       }
                   11157:       if(match == 0){
1.349     brouard  11158:        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);
                   11159:        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  11160:        return 1;
                   11161:       }
                   11162:       match=0;
                   11163:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11164:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11165:          /* modelresult[k2]=k1;*/
1.342     brouard  11166:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11167:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11168:          break;
                   11169:        }
                   11170:       }
                   11171:       if(match == 0){
1.349     brouard  11172:        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);
                   11173:        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  11174:        return 1;
                   11175:       }
                   11176:     }/* End of testing */
1.333     brouard  11177:   }/* End loop cptcovt */
1.235     brouard  11178:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11179:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11180:   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)
                   11181:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11182:     match=0;
1.318     brouard  11183:     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  11184:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11185:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11186:          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  11187:          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  11188:          ++match;
                   11189:        }
                   11190:       }
                   11191:     }
                   11192:     if(match == 0){
1.338     brouard  11193:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11194:       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  11195:       return 1;
1.234     brouard  11196:     }else if(match > 1){
1.338     brouard  11197:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11198:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11199:       return 1;
1.234     brouard  11200:     }
                   11201:   }
1.334     brouard  11202:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11203:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11204:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11205:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11206:   /* 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*/
                   11207:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11208:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11209:   /*    1 0 0 0 */
                   11210:   /*    2 1 0 0 */
                   11211:   /*    3 0 1 0 */ 
1.330     brouard  11212:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11213:   /*    5 0 0 1 */
1.330     brouard  11214:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11215:   /*    7 0 1 1 */
                   11216:   /*    8 1 1 1 */
1.237     brouard  11217:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11218:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11219:   /* V5*age V5 known which value for nres?  */
                   11220:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11221:   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.
                   11222:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11223:     /* k counting number of combination of single dummies in the equation model */
                   11224:     /* k4 counting single dummies in the equation model */
                   11225:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11226:     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  11227:        /* 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  11228:       /* 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  11229:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11230:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11231:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11232:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11233:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11234:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11235:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11236:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11237:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11238:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11239:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11240:       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  11241:       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  11242:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11243:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11244:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11245:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11246:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11247:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11248:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11249:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11250:       /* 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  11251:       k4++;;
1.331     brouard  11252:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11253:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11254:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11255:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11256:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11257:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11258:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11259:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11260:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11261:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11262:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11263:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11264:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11265:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11266:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11267:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11268:       /* 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  11269:       k4q++;;
1.350   ! brouard  11270:     }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"*/
        !          11271:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11272:       /* Wrong we want the value of variable name Tvar[k1] */
1.350   ! brouard  11273:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
        !          11274:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
        !          11275:       /* 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]]); */
        !          11276:       }else{
        !          11277:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
        !          11278:        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)*/
        !          11279:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
        !          11280:        precov[nres][k1]=Tvalsel[k3];
        !          11281:       }
1.342     brouard  11282:       /* 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  11283:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350   ! brouard  11284:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
        !          11285:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
        !          11286:       /* 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]]); */
        !          11287:       }else{
        !          11288:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
        !          11289:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
        !          11290:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
        !          11291:        precov[nres][k1]=Tvalsel[k3q];
        !          11292:       }
1.342     brouard  11293:       /* 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  11294:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11295:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11296:       /* 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  11297:     }else{
1.332     brouard  11298:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11299:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11300:     }
                   11301:   }
1.234     brouard  11302:   
1.334     brouard  11303:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11304:   return (0);
                   11305: }
1.235     brouard  11306: 
1.230     brouard  11307: int decodemodel( char model[], int lastobs)
                   11308:  /**< This routine decodes the model and returns:
1.224     brouard  11309:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11310:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11311:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11312:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11313:        * - cptcovage number of covariates with age*products =2
                   11314:        * - cptcovs number of simple covariates
1.339     brouard  11315:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11316:        * - 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  11317:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11318:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11319:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11320:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11321:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11322:        */
1.319     brouard  11323: /* 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  11324: {
1.238     brouard  11325:   int i, j, k, ks, v;
1.349     brouard  11326:   int n,m;
                   11327:   int  j1, k1, k11, k12, k2, k3, k4;
                   11328:   char modelsav[300];
                   11329:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11330:   char *strpt;
1.349     brouard  11331:   int  **existcomb;
                   11332:   
                   11333:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11334:   for(i=1;i<=NCOVMAX;i++)
                   11335:     for(j=1;j<=NCOVMAX;j++)
                   11336:       existcomb[i][j]=0;
                   11337:     
1.145     brouard  11338:   /*removespace(model);*/
1.136     brouard  11339:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11340:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11341:     if (strstr(model,"AGE") !=0){
1.192     brouard  11342:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11343:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11344:       return 1;
                   11345:     }
1.141     brouard  11346:     if (strstr(model,"v") !=0){
1.338     brouard  11347:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11348:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11349:       return 1;
                   11350:     }
1.187     brouard  11351:     strcpy(modelsav,model); 
                   11352:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11353:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11354:       if(strpt != model){
1.338     brouard  11355:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11356:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11357:  corresponding column of parameters.\n",model);
1.338     brouard  11358:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11359:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11360:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11361:        return 1;
1.225     brouard  11362:       }
1.187     brouard  11363:       nagesqr=1;
                   11364:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11365:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11366:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11367:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11368:       else 
1.234     brouard  11369:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11370:     }else
                   11371:       nagesqr=0;
1.349     brouard  11372:     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  11373:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11374:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.349     brouard  11375:       cptcovs=j+1-j1; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  */
1.187     brouard  11376:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11377:                     * cst, age and age*age 
                   11378:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11379:       /* including age products which are counted in cptcovage.
                   11380:        * but the covariates which are products must be treated 
                   11381:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11382:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11383:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11384:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11385:       cptcovprodage=0;
                   11386:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11387:       
1.187     brouard  11388:       /*   Design
                   11389:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11390:        *  <          ncovcol=8                >
                   11391:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11392:        *   k=  1    2      3       4     5       6      7        8
                   11393:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11394:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11395:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11396:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11397:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11398:        *  Tage[++cptcovage]=k
1.345     brouard  11399:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11400:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11401:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11402:        *  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
                   11403:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11404:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11405:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11406:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11407:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11408:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11409:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11410:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11411:        * p Tprod[1]@2={                         6, 5}
                   11412:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11413:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11414:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11415:        *How to reorganize? Tvars(orted)
1.187     brouard  11416:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11417:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11418:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11419:        * Struct []
                   11420:        */
1.225     brouard  11421:       
1.187     brouard  11422:       /* This loop fills the array Tvar from the string 'model'.*/
                   11423:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11424:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11425:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11426:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11427:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11428:       /*       k=1 Tvar[1]=2 (from V2) */
                   11429:       /*       k=5 Tvar[5] */
                   11430:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11431:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11432:       /*       } */
1.198     brouard  11433:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11434:       /*
                   11435:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11436:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11437:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11438:       }
1.187     brouard  11439:       cptcovage=0;
1.319     brouard  11440:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11441:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11442:                                         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" */
                   11443:        if (nbocc(modelsav,'+')==0)
                   11444:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11445:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11446:        /*scanf("%d",i);*/
1.349     brouard  11447:        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 */
                   11448:          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  */
                   11449:          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   */
                   11450:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11451:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11452:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11453:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11454:              /* We want strb=Vn*Vm */
                   11455:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11456:                 strcpy(strb,strd);
                   11457:                 strcat(strb,"*");
                   11458:                 strcat(strb,stre);
                   11459:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11460:                 strcpy(strb,strf);
                   11461:                 strcat(strb,"*");
                   11462:                 strcat(strb,stre);
                   11463:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11464:               }
                   11465:              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]]]);
                   11466:              FixedV[Tvar[Tage[k]]]=0; /* HERY not sure */
                   11467:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11468:              strcpy(stre,strb); /* save full b in stre */
                   11469:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11470:              strcpy(strf,strc); /* save short c in new short f */
                   11471:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11472:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11473:             }
                   11474:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11475:             /* 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 *\/ */
                   11476:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11477:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11478:            n=atoi(stre);
1.234     brouard  11479:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11480:            m=atoi(strc);
                   11481:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11482:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11483:            if(existcomb[n][m] == 0){
                   11484:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11485:              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);
                   11486:              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);
                   11487:              fflush(ficlog);
                   11488:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11489:              k12++;
                   11490:              existcomb[n][m]=k1;
                   11491:              existcomb[m][n]=k1;
                   11492:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11493:              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*/
                   11494:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11495:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11496:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11497:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11498:              Tvardk[k][2] =n; /* n 4 for V4*/
                   11499: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */
                   11500:              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 */
                   11501:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11502:                  /* Computes the new covariate which is a product of
                   11503:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11504:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11505:                }
                   11506:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11507:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11508:                k12++;
                   11509:                FixedV[ncovcolt+k12]=0;
                   11510:              }else{ /*End of FixedV */
                   11511:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11512:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11513:                k12++;
                   11514:                FixedV[ncovcolt+k12]=1;
                   11515:              }
                   11516:            }else{  /* k1 Vn*Vm already exists */
                   11517:              k11=existcomb[n][m];
                   11518:              Tposprod[k]=k11; /* OK */
                   11519:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11520:              Tvardk[k][1]=m;
                   11521:              Tvardk[k][2]=n;
                   11522:              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 */
                   11523:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11524:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11525:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11526:                Tvar[Tage[cptcovage]]=k1;
                   11527:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11528:                k12++;
                   11529:                FixedV[ncovcolt+k12]=0;
                   11530:              }else{ /* Already exists but time varying (and age) */
                   11531:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11532:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11533:                /* Tvar[Tage[cptcovage]]=k1; */
                   11534:                cptcovprodvage++;
                   11535:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11536:                k12++;
                   11537:                FixedV[ncovcolt+k12]=1;
                   11538:              }
                   11539:            }
                   11540:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11541:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11542:          } 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 */
                   11543:             cptcovprod++;
                   11544:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11545:               /* covar is not filled and then is empty */
                   11546:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11547:               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 */
                   11548:               Typevar[k]=1;  /* 1 for age product */
                   11549:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11550:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11551:              if( FixedV[Tvar[k]] == 0){
                   11552:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11553:              }else{
                   11554:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11555:              }
                   11556:               /*printf("stre=%s ", stre);*/
                   11557:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11558:               cutl(stre,strb,strc,'V');
                   11559:               Tvar[k]=atoi(stre);
                   11560:               Typevar[k]=1;  /* 1 for age product */
                   11561:               cptcovage++;
                   11562:               Tage[cptcovage]=k;
                   11563:              if( FixedV[Tvar[k]] == 0){
                   11564:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11565:              }else{
                   11566:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11567:              }
1.349     brouard  11568:             }else{ /*  for product Vn*Vm */
                   11569:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11570:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11571:              n=atoi(stre);
                   11572:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11573:              m=atoi(strc);
                   11574:              k1++;
                   11575:              cptcovprodnoage++;
                   11576:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11577:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11578:                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]);
                   11579:                fflush(ficlog);
                   11580:                k11=existcomb[n][m];
                   11581:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11582:                Tposprod[k]=k11;
                   11583:                Tprod[k11]=k;
                   11584:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11585:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11586:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11587:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11588:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11589:                existcomb[n][m]=k1;
                   11590:                existcomb[m][n]=k1;
                   11591:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11592:                                                    because this model-covariate is a construction we invent a new column
                   11593:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11594:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11595:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11596:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11597:                /* Please remark that the new variables are model dependent */
                   11598:                /* If we have 4 variable but the model uses only 3, like in
                   11599:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11600:                 *  k=     1     2      3   4     5        6        7       8
                   11601:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11602:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11603:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11604:                 */
                   11605:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11606:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11607:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11608:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11609:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11610:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11611:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11612:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11613:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11614:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11615:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11616:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11617:                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 */
                   11618:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11619:                    /* Computes the new covariate which is a product of
                   11620:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11621:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11622:                  }
                   11623:                  /* TvarVV[k2]=n; */
                   11624:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11625:                  /* TvarVV[k2+1]=m; */
                   11626:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11627:                }else{ /* not FixedV */
                   11628:                  /* TvarVV[k2]=n; */
                   11629:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11630:                  /* TvarVV[k2+1]=m; */
                   11631:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11632:                }                 
                   11633:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11634:            } /*  End of product Vn*Vm */
                   11635:           } /* End of age*double product or simple product */
                   11636:        }else { /* not a product */
1.234     brouard  11637:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11638:          /*  scanf("%d",i);*/
                   11639:          cutl(strd,strc,strb,'V');
                   11640:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11641:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11642:          Tvar[k]=atoi(strd);
                   11643:          Typevar[k]=0;  /* 0 for simple covariates */
                   11644:        }
                   11645:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11646:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11647:                                  scanf("%d",i);*/
1.187     brouard  11648:       } /* end of loop + on total covariates */
                   11649:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11650:   } /* end if strlen(model == 0) */
1.349     brouard  11651:   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  */
                   11652: 
1.136     brouard  11653:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11654:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11655:   
1.136     brouard  11656:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11657:      printf("cptcovprod=%d ", cptcovprod);
                   11658:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11659:      scanf("%d ",i);*/
                   11660: 
                   11661: 
1.230     brouard  11662: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11663:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11664: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11665:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11666:    k =           1    2   3     4       5       6      7      8        9
                   11667:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11668:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11669:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11670:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11671:          Tmodelind[combination of covar]=k;
1.225     brouard  11672: */  
                   11673: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11674:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11675:   /* 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  11676:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11677:   printf("Model=1+age+%s\n\
1.349     brouard  11678: 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  11679: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11680: 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  11681:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11682: 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  11683: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11684: 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  11685:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11686:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.349     brouard  11687:   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  11688:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11689:       Fixed[k]= 0;
                   11690:       Dummy[k]= 0;
1.225     brouard  11691:       ncoveff++;
1.232     brouard  11692:       ncovf++;
1.234     brouard  11693:       nsd++;
                   11694:       modell[k].maintype= FTYPE;
                   11695:       TvarsD[nsd]=Tvar[k];
                   11696:       TvarsDind[nsd]=k;
1.330     brouard  11697:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11698:       TvarF[ncovf]=Tvar[k];
                   11699:       TvarFind[ncovf]=k;
                   11700:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11701:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11702:     /* }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  11703:     }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  11704:       Fixed[k]= 0;
                   11705:       Dummy[k]= 1;
1.230     brouard  11706:       nqfveff++;
1.234     brouard  11707:       modell[k].maintype= FTYPE;
                   11708:       modell[k].subtype= FQ;
                   11709:       nsq++;
1.334     brouard  11710:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11711:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11712:       ncovf++;
1.234     brouard  11713:       TvarF[ncovf]=Tvar[k];
                   11714:       TvarFind[ncovf]=k;
1.231     brouard  11715:       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  11716:       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  11717:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11718:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11719:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11720:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11721:       ncovvt++;
                   11722:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11723:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11724: 
1.227     brouard  11725:       Fixed[k]= 1;
                   11726:       Dummy[k]= 0;
1.225     brouard  11727:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11728:       modell[k].maintype= VTYPE;
                   11729:       modell[k].subtype= VD;
                   11730:       nsd++;
                   11731:       TvarsD[nsd]=Tvar[k];
                   11732:       TvarsDind[nsd]=k;
1.330     brouard  11733:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11734:       ncovv++; /* Only simple time varying variables */
                   11735:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11736:       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  11737:       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 */
                   11738:       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  11739:       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);
                   11740:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11741:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11742:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11743:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11744:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11745:       ncovvt++;
                   11746:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11747:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11748:       
1.234     brouard  11749:       Fixed[k]= 1;
                   11750:       Dummy[k]= 1;
                   11751:       nqtveff++;
                   11752:       modell[k].maintype= VTYPE;
                   11753:       modell[k].subtype= VQ;
                   11754:       ncovv++; /* Only simple time varying variables */
                   11755:       nsq++;
1.334     brouard  11756:       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) */
                   11757:       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  11758:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11759:       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  11760:       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 */
                   11761:       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  11762:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11763:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11764:       /* 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  11765:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11766:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11767:       ncova++;
                   11768:       TvarA[ncova]=Tvar[k];
                   11769:       TvarAind[ncova]=k;
1.349     brouard  11770:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11771:       /** 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  11772:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11773:        Fixed[k]= 2;
                   11774:        Dummy[k]= 2;
                   11775:        modell[k].maintype= ATYPE;
                   11776:        modell[k].subtype= APFD;
1.349     brouard  11777:        ncovta++;
                   11778:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11779:        TvarAVVAind[ncovta]=k;
1.240     brouard  11780:        /* ncoveff++; */
1.227     brouard  11781:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11782:        Fixed[k]= 2;
                   11783:        Dummy[k]= 3;
                   11784:        modell[k].maintype= ATYPE;
                   11785:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11786:        ncovta++;
                   11787:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11788:        TvarAVVAind[ncovta]=k;
1.240     brouard  11789:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11790:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11791:        Fixed[k]= 3;
                   11792:        Dummy[k]= 2;
                   11793:        modell[k].maintype= ATYPE;
                   11794:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11795:        ncovva++;
                   11796:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11797:        TvarVVAind[ncovva]=k;
                   11798:        ncovta++;
                   11799:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11800:        TvarAVVAind[ncovta]=k;
1.240     brouard  11801:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11802:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11803:        Fixed[k]= 3;
                   11804:        Dummy[k]= 3;
                   11805:        modell[k].maintype= ATYPE;
                   11806:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11807:        ncovva++;
                   11808:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11809:        TvarVVAind[ncovva]=k;
                   11810:        ncovta++;
                   11811:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11812:        TvarAVVAind[ncovta]=k;
1.240     brouard  11813:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11814:       }
1.349     brouard  11815:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11816:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11817:       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 */
                   11818:       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]]);
                   11819:        Fixed[k]= 0;
                   11820:        Dummy[k]= 0;
                   11821:        ncoveff++;
                   11822:        ncovf++;
                   11823:        /* ncovv++; */
                   11824:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11825:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11826:        /* ncovv++; */
                   11827:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11828:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11829:        modell[k].maintype= FTYPE;
                   11830:        TvarF[ncovf]=Tvar[k];
                   11831:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11832:        TvarFind[ncovf]=k;
                   11833:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11834:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11835:       }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  */
                   11836:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11837:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11838:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11839:        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 */
                   11840:        ncovvt++;
                   11841:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11842:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11843:        ncovvt++;
                   11844:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11845:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11846:        
                   11847:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11848:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11849:        
                   11850:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11851:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11852:            Fixed[k]= 1;
                   11853:            Dummy[k]= 0;
                   11854:            modell[k].maintype= FTYPE;
                   11855:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11856:            ncovf++; /* Fixed variables without age */
                   11857:            TvarF[ncovf]=Tvar[k];
                   11858:            TvarFind[ncovf]=k;
                   11859:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11860:            Fixed[k]= 0;  /* Fixed product */
                   11861:            Dummy[k]= 1;
                   11862:            modell[k].maintype= FTYPE;
                   11863:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11864:            ncovf++; /* Varying variables without age */
                   11865:            TvarF[ncovf]=Tvar[k];
                   11866:            TvarFind[ncovf]=k;
                   11867:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11868:            Fixed[k]= 1;
                   11869:            Dummy[k]= 0;
                   11870:            modell[k].maintype= VTYPE;
                   11871:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11872:            ncovv++; /* Varying variables without age */
                   11873:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11874:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11875:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11876:            Fixed[k]= 1;
                   11877:            Dummy[k]= 1;
                   11878:            modell[k].maintype= VTYPE;
                   11879:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11880:            ncovv++; /* Varying variables without age */
                   11881:            TvarV[ncovv]=Tvar[k];
                   11882:            TvarVind[ncovv]=k;
                   11883:          }
                   11884:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11885:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11886:            Fixed[k]= 0;  /*  Fixed product */
                   11887:            Dummy[k]= 1;
                   11888:            modell[k].maintype= FTYPE;
                   11889:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11890:            ncovf++; /* Fixed variables without age */
                   11891:            TvarF[ncovf]=Tvar[k];
                   11892:            TvarFind[ncovf]=k;
                   11893:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11894:            Fixed[k]= 1;
                   11895:            Dummy[k]= 1;
                   11896:            modell[k].maintype= VTYPE;
                   11897:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11898:            ncovv++; /* Varying variables without age */
                   11899:            TvarV[ncovv]=Tvar[k];
                   11900:            TvarVind[ncovv]=k;
                   11901:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11902:            Fixed[k]= 1;
                   11903:            Dummy[k]= 1;
                   11904:            modell[k].maintype= VTYPE;
                   11905:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11906:            ncovv++; /* Varying variables without age */
                   11907:            TvarV[ncovv]=Tvar[k];
                   11908:            TvarVind[ncovv]=k;
                   11909:            ncovv++; /* Varying variables without age */
                   11910:            TvarV[ncovv]=Tvar[k];
                   11911:            TvarVind[ncovv]=k;
                   11912:          }
                   11913:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11914:          if(Tvard[k1][2] <=ncovcol){
                   11915:            Fixed[k]= 1;
                   11916:            Dummy[k]= 1;
                   11917:            modell[k].maintype= VTYPE;
                   11918:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   11919:            ncovv++; /* Varying variables without age */
                   11920:            TvarV[ncovv]=Tvar[k];
                   11921:            TvarVind[ncovv]=k;
                   11922:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11923:            Fixed[k]= 1;
                   11924:            Dummy[k]= 1;
                   11925:            modell[k].maintype= VTYPE;
                   11926:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   11927:            ncovv++; /* Varying variables without age */
                   11928:            TvarV[ncovv]=Tvar[k];
                   11929:            TvarVind[ncovv]=k;
                   11930:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11931:            Fixed[k]= 1;
                   11932:            Dummy[k]= 0;
                   11933:            modell[k].maintype= VTYPE;
                   11934:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   11935:            ncovv++; /* Varying variables without age */
                   11936:            TvarV[ncovv]=Tvar[k];
                   11937:            TvarVind[ncovv]=k;
                   11938:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11939:            Fixed[k]= 1;
                   11940:            Dummy[k]= 1;
                   11941:            modell[k].maintype= VTYPE;
                   11942:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   11943:            ncovv++; /* Varying variables without age */
                   11944:            TvarV[ncovv]=Tvar[k];
                   11945:            TvarVind[ncovv]=k;
                   11946:          }
                   11947:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   11948:          if(Tvard[k1][2] <=ncovcol){
                   11949:            Fixed[k]= 1;
                   11950:            Dummy[k]= 1;
                   11951:            modell[k].maintype= VTYPE;
                   11952:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   11953:            ncovv++; /* Varying variables without age */
                   11954:            TvarV[ncovv]=Tvar[k];
                   11955:            TvarVind[ncovv]=k;
                   11956:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11957:            Fixed[k]= 1;
                   11958:            Dummy[k]= 1;
                   11959:            modell[k].maintype= VTYPE;
                   11960:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   11961:            ncovv++; /* Varying variables without age */
                   11962:            TvarV[ncovv]=Tvar[k];
                   11963:            TvarVind[ncovv]=k;
                   11964:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11965:            Fixed[k]= 1;
                   11966:            Dummy[k]= 1;
                   11967:            modell[k].maintype= VTYPE;
                   11968:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   11969:            ncovv++; /* Varying variables without age */
                   11970:            TvarV[ncovv]=Tvar[k];
                   11971:            TvarVind[ncovv]=k;
                   11972:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11973:            Fixed[k]= 1;
                   11974:            Dummy[k]= 1;
                   11975:            modell[k].maintype= VTYPE;
                   11976:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   11977:            ncovv++; /* Varying variables without age */
                   11978:            TvarV[ncovv]=Tvar[k];
                   11979:            TvarVind[ncovv]=k;
                   11980:          }
                   11981:        }else{
                   11982:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11983:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11984:        } /*end k1*/
                   11985:       }
                   11986:     }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  11987:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  11988:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11989:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11990:       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 */
                   11991:       ncova++;
                   11992:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11993:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11994:       ncova++;
                   11995:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11996:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  11997: 
1.349     brouard  11998:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11999:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12000:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12001:        ncovta++;
                   12002:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12003:        TvarAVVAind[ncovta]=k;
                   12004:        ncovta++;
                   12005:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12006:        TvarAVVAind[ncovta]=k;
                   12007:       }else{
                   12008:        ncovva++;  /* HERY  reached */
                   12009:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12010:        TvarVVAind[ncovva]=k;
                   12011:        ncovva++;
                   12012:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12013:        TvarVVAind[ncovva]=k;
                   12014:        ncovta++;
                   12015:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12016:        TvarAVVAind[ncovta]=k;
                   12017:        ncovta++;
                   12018:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12019:        TvarAVVAind[ncovta]=k;
                   12020:       }
1.339     brouard  12021:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12022:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12023:          Fixed[k]= 2;
                   12024:          Dummy[k]= 2;
1.240     brouard  12025:          modell[k].maintype= FTYPE;
                   12026:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12027:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12028:          /* TvarFind[ncova]=k; */
1.339     brouard  12029:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12030:          Fixed[k]= 2;  /* Fixed product */
                   12031:          Dummy[k]= 3;
1.240     brouard  12032:          modell[k].maintype= FTYPE;
                   12033:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12034:          /* TvarF[ncova]=Tvar[k]; */
                   12035:          /* TvarFind[ncova]=k; */
1.339     brouard  12036:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12037:          Fixed[k]= 3;
                   12038:          Dummy[k]= 2;
1.240     brouard  12039:          modell[k].maintype= VTYPE;
                   12040:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12041:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12042:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12043:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12044:          Fixed[k]= 3;
                   12045:          Dummy[k]= 3;
1.240     brouard  12046:          modell[k].maintype= VTYPE;
                   12047:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12048:          /* ncovv++; /\* Varying variables without age *\/ */
                   12049:          /* TvarV[ncovv]=Tvar[k]; */
                   12050:          /* TvarVind[ncovv]=k; */
1.240     brouard  12051:        }
1.339     brouard  12052:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12053:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12054:          Fixed[k]= 2;  /*  Fixed product */
                   12055:          Dummy[k]= 2;
1.240     brouard  12056:          modell[k].maintype= FTYPE;
                   12057:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12058:          /* ncova++; /\* Fixed variables with age *\/ */
                   12059:          /* TvarF[ncovf]=Tvar[k]; */
                   12060:          /* TvarFind[ncovf]=k; */
1.339     brouard  12061:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12062:          Fixed[k]= 2;
                   12063:          Dummy[k]= 3;
1.240     brouard  12064:          modell[k].maintype= VTYPE;
                   12065:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12066:          /* ncova++; /\* Varying variables with age *\/ */
                   12067:          /* TvarV[ncova]=Tvar[k]; */
                   12068:          /* TvarVind[ncova]=k; */
1.339     brouard  12069:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12070:          Fixed[k]= 3;
                   12071:          Dummy[k]= 2;
1.240     brouard  12072:          modell[k].maintype= VTYPE;
                   12073:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12074:          ncova++; /* Varying variables without age */
                   12075:          TvarV[ncova]=Tvar[k];
                   12076:          TvarVind[ncova]=k;
                   12077:          /* ncova++; /\* Varying variables without age *\/ */
                   12078:          /* TvarV[ncova]=Tvar[k]; */
                   12079:          /* TvarVind[ncova]=k; */
1.240     brouard  12080:        }
1.339     brouard  12081:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12082:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12083:          Fixed[k]= 2;
                   12084:          Dummy[k]= 2;
1.240     brouard  12085:          modell[k].maintype= VTYPE;
                   12086:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12087:          /* ncova++; /\* Varying variables with age *\/ */
                   12088:          /* TvarV[ncova]=Tvar[k]; */
                   12089:          /* TvarVind[ncova]=k; */
1.240     brouard  12090:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12091:          Fixed[k]= 2;
                   12092:          Dummy[k]= 3;
1.240     brouard  12093:          modell[k].maintype= VTYPE;
                   12094:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12095:          /* ncova++; /\* Varying variables with age *\/ */
                   12096:          /* TvarV[ncova]=Tvar[k]; */
                   12097:          /* TvarVind[ncova]=k; */
1.240     brouard  12098:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
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 time varying dummy * time varying dummy */
1.349     brouard  12103:          /* ncova++; /\* Varying variables with age *\/ */
                   12104:          /* TvarV[ncova]=Tvar[k]; */
                   12105:          /* TvarVind[ncova]=k; */
1.240     brouard  12106:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12107:          Fixed[k]= 3;
                   12108:          Dummy[k]= 3;
1.240     brouard  12109:          modell[k].maintype= VTYPE;
                   12110:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12111:          /* ncova++; /\* Varying variables with age *\/ */
                   12112:          /* TvarV[ncova]=Tvar[k]; */
                   12113:          /* TvarVind[ncova]=k; */
1.240     brouard  12114:        }
1.339     brouard  12115:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12116:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12117:          Fixed[k]= 2;
                   12118:          Dummy[k]= 2;
1.240     brouard  12119:          modell[k].maintype= VTYPE;
                   12120:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12121:          /* ncova++; /\* Varying variables with age *\/ */
                   12122:          /* TvarV[ncova]=Tvar[k]; */
                   12123:          /* TvarVind[ncova]=k; */
1.240     brouard  12124:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12125:          Fixed[k]= 2;
                   12126:          Dummy[k]= 3;
1.240     brouard  12127:          modell[k].maintype= VTYPE;
                   12128:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12129:          /* ncova++; /\* Varying variables with age *\/ */
                   12130:          /* TvarV[ncova]=Tvar[k]; */
                   12131:          /* TvarVind[ncova]=k; */
1.240     brouard  12132:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12133:          Fixed[k]= 3;
                   12134:          Dummy[k]= 2;
1.240     brouard  12135:          modell[k].maintype= VTYPE;
                   12136:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12137:          /* ncova++; /\* Varying variables with age *\/ */
                   12138:          /* TvarV[ncova]=Tvar[k]; */
                   12139:          /* TvarVind[ncova]=k; */
1.240     brouard  12140:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12141:          Fixed[k]= 3;
                   12142:          Dummy[k]= 3;
1.240     brouard  12143:          modell[k].maintype= VTYPE;
                   12144:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12145:          /* ncova++; /\* Varying variables with age *\/ */
                   12146:          /* TvarV[ncova]=Tvar[k]; */
                   12147:          /* TvarVind[ncova]=k; */
1.240     brouard  12148:        }
1.227     brouard  12149:       }else{
1.240     brouard  12150:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12151:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12152:       } /*end k1*/
1.349     brouard  12153:     } else{
1.226     brouard  12154:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12155:       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  12156:     }
1.342     brouard  12157:     /* 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]); */
                   12158:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12159:     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]);
                   12160:   }
1.349     brouard  12161:   ncovvta=ncovva;
1.227     brouard  12162:   /* Searching for doublons in the model */
                   12163:   for(k1=1; k1<= cptcovt;k1++){
                   12164:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12165:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12166:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12167:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12168:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12169:            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]);
                   12170:            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  12171:            return(1);
                   12172:          }
                   12173:        }else if (Typevar[k1] ==2){
                   12174:          k3=Tposprod[k1];
                   12175:          k4=Tposprod[k2];
                   12176:          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  12177:            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]]);
                   12178:            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  12179:            return(1);
                   12180:          }
                   12181:        }
1.227     brouard  12182:       }
                   12183:     }
1.225     brouard  12184:   }
                   12185:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12186:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12187:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12188:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12189: 
                   12190:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12191:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12192:   /*endread:*/
1.225     brouard  12193:   printf("Exiting decodemodel: ");
                   12194:   return (1);
1.136     brouard  12195: }
                   12196: 
1.169     brouard  12197: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12198: {/* Check ages at death */
1.136     brouard  12199:   int i, m;
1.218     brouard  12200:   int firstone=0;
                   12201:   
1.136     brouard  12202:   for (i=1; i<=imx; i++) {
                   12203:     for(m=2; (m<= maxwav); m++) {
                   12204:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12205:        anint[m][i]=9999;
1.216     brouard  12206:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12207:          s[m][i]=-1;
1.136     brouard  12208:       }
                   12209:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12210:        *nberr = *nberr + 1;
1.218     brouard  12211:        if(firstone == 0){
                   12212:          firstone=1;
1.260     brouard  12213:        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  12214:        }
1.262     brouard  12215:        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  12216:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12217:       }
                   12218:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12219:        (*nberr)++;
1.259     brouard  12220:        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  12221:        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  12222:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12223:       }
                   12224:     }
                   12225:   }
                   12226: 
                   12227:   for (i=1; i<=imx; i++)  {
                   12228:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12229:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12230:       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  12231:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12232:          if(agedc[i]>0){
                   12233:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12234:              agev[m][i]=agedc[i];
1.214     brouard  12235:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12236:            }else {
1.136     brouard  12237:              if ((int)andc[i]!=9999){
                   12238:                nbwarn++;
                   12239:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12240:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12241:                agev[m][i]=-1;
                   12242:              }
                   12243:            }
1.169     brouard  12244:          } /* agedc > 0 */
1.214     brouard  12245:        } /* end if */
1.136     brouard  12246:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12247:                                 years but with the precision of a month */
                   12248:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12249:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12250:            agev[m][i]=1;
                   12251:          else if(agev[m][i] < *agemin){ 
                   12252:            *agemin=agev[m][i];
                   12253:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12254:          }
                   12255:          else if(agev[m][i] >*agemax){
                   12256:            *agemax=agev[m][i];
1.156     brouard  12257:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12258:          }
                   12259:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12260:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12261:        } /* en if 9*/
1.136     brouard  12262:        else { /* =9 */
1.214     brouard  12263:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12264:          agev[m][i]=1;
                   12265:          s[m][i]=-1;
                   12266:        }
                   12267:       }
1.214     brouard  12268:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12269:        agev[m][i]=1;
1.214     brouard  12270:       else{
                   12271:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12272:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12273:        agev[m][i]=0;
                   12274:       }
                   12275:     } /* End for lastpass */
                   12276:   }
1.136     brouard  12277:     
                   12278:   for (i=1; i<=imx; i++)  {
                   12279:     for(m=firstpass; (m<=lastpass); m++){
                   12280:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12281:        (*nberr)++;
1.136     brouard  12282:        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);     
                   12283:        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);     
                   12284:        return 1;
                   12285:       }
                   12286:     }
                   12287:   }
                   12288: 
                   12289:   /*for (i=1; i<=imx; i++){
                   12290:   for (m=firstpass; (m<lastpass); m++){
                   12291:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12292: }
                   12293: 
                   12294: }*/
                   12295: 
                   12296: 
1.139     brouard  12297:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12298:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12299: 
                   12300:   return (0);
1.164     brouard  12301:  /* endread:*/
1.136     brouard  12302:     printf("Exiting calandcheckages: ");
                   12303:     return (1);
                   12304: }
                   12305: 
1.172     brouard  12306: #if defined(_MSC_VER)
                   12307: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12308: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12309: //#include "stdafx.h"
                   12310: //#include <stdio.h>
                   12311: //#include <tchar.h>
                   12312: //#include <windows.h>
                   12313: //#include <iostream>
                   12314: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12315: 
                   12316: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12317: 
                   12318: BOOL IsWow64()
                   12319: {
                   12320:        BOOL bIsWow64 = FALSE;
                   12321: 
                   12322:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12323:        //  (HANDLE, PBOOL);
                   12324: 
                   12325:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12326: 
                   12327:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12328:        const char funcName[] = "IsWow64Process";
                   12329:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12330:                GetProcAddress(module, funcName);
                   12331: 
                   12332:        if (NULL != fnIsWow64Process)
                   12333:        {
                   12334:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12335:                        &bIsWow64))
                   12336:                        //throw std::exception("Unknown error");
                   12337:                        printf("Unknown error\n");
                   12338:        }
                   12339:        return bIsWow64 != FALSE;
                   12340: }
                   12341: #endif
1.177     brouard  12342: 
1.191     brouard  12343: void syscompilerinfo(int logged)
1.292     brouard  12344: {
                   12345: #include <stdint.h>
                   12346: 
                   12347:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12348:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12349:    /* /GS /W3 /Gy
                   12350:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12351:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12352:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12353:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12354:    */ 
                   12355:    /* 64 bits */
1.185     brouard  12356:    /*
                   12357:      /GS /W3 /Gy
                   12358:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12359:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12360:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12361:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12362:    /* Optimization are useless and O3 is slower than O2 */
                   12363:    /*
                   12364:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12365:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12366:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12367:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12368:    */
1.186     brouard  12369:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12370:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12371:       /PDB:"visual studio
                   12372:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12373:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12374:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12375:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12376:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12377:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12378:       uiAccess='false'"
                   12379:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12380:       /NOLOGO /TLBID:1
                   12381:    */
1.292     brouard  12382: 
                   12383: 
1.177     brouard  12384: #if defined __INTEL_COMPILER
1.178     brouard  12385: #if defined(__GNUC__)
                   12386:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12387: #endif
1.177     brouard  12388: #elif defined(__GNUC__) 
1.179     brouard  12389: #ifndef  __APPLE__
1.174     brouard  12390: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12391: #endif
1.177     brouard  12392:    struct utsname sysInfo;
1.178     brouard  12393:    int cross = CROSS;
                   12394:    if (cross){
                   12395:           printf("Cross-");
1.191     brouard  12396:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12397:    }
1.174     brouard  12398: #endif
                   12399: 
1.191     brouard  12400:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12401: #if defined(__clang__)
1.191     brouard  12402:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12403: #endif
                   12404: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12405:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12406: #endif
                   12407: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12408:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12409: #endif
                   12410: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12411:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12412: #endif
                   12413: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12414:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12415: #endif
                   12416: #if defined(_MSC_VER)
1.191     brouard  12417:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12418: #endif
                   12419: #if defined(__PGI)
1.191     brouard  12420:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12421: #endif
                   12422: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12423:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12424: #endif
1.191     brouard  12425:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12426:    
1.167     brouard  12427: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12428: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12429:     // Windows (x64 and x86)
1.191     brouard  12430:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12431: #elif __unix__ // all unices, not all compilers
                   12432:     // Unix
1.191     brouard  12433:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12434: #elif __linux__
                   12435:     // linux
1.191     brouard  12436:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12437: #elif __APPLE__
1.174     brouard  12438:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12439:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12440: #endif
                   12441: 
                   12442: /*  __MINGW32__          */
                   12443: /*  __CYGWIN__  */
                   12444: /* __MINGW64__  */
                   12445: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12446: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12447: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12448: /* _WIN64  // Defined for applications for Win64. */
                   12449: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12450: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12451: 
1.167     brouard  12452: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12453:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12454: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12455:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12456: #else
1.191     brouard  12457:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12458: #endif
                   12459: 
1.169     brouard  12460: #if defined(__GNUC__)
                   12461: # if defined(__GNUC_PATCHLEVEL__)
                   12462: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12463:                             + __GNUC_MINOR__ * 100 \
                   12464:                             + __GNUC_PATCHLEVEL__)
                   12465: # else
                   12466: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12467:                             + __GNUC_MINOR__ * 100)
                   12468: # endif
1.174     brouard  12469:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12470:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12471: 
                   12472:    if (uname(&sysInfo) != -1) {
                   12473:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12474:         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  12475:    }
                   12476:    else
                   12477:       perror("uname() error");
1.179     brouard  12478:    //#ifndef __INTEL_COMPILER 
                   12479: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12480:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12481:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12482: #endif
1.169     brouard  12483: #endif
1.172     brouard  12484: 
1.286     brouard  12485:    //   void main ()
1.172     brouard  12486:    //   {
1.169     brouard  12487: #if defined(_MSC_VER)
1.174     brouard  12488:    if (IsWow64()){
1.191     brouard  12489:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12490:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12491:    }
                   12492:    else{
1.191     brouard  12493:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12494:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12495:    }
1.172     brouard  12496:    //     printf("\nPress Enter to continue...");
                   12497:    //     getchar();
                   12498:    //   }
                   12499: 
1.169     brouard  12500: #endif
                   12501:    
1.167     brouard  12502: 
1.219     brouard  12503: }
1.136     brouard  12504: 
1.219     brouard  12505: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12506:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12507:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12508:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12509:   /* double ftolpl = 1.e-10; */
1.180     brouard  12510:   double age, agebase, agelim;
1.203     brouard  12511:   double tot;
1.180     brouard  12512: 
1.202     brouard  12513:   strcpy(filerespl,"PL_");
                   12514:   strcat(filerespl,fileresu);
                   12515:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12516:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12517:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12518:   }
1.288     brouard  12519:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12520:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12521:   pstamp(ficrespl);
1.288     brouard  12522:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12523:   fprintf(ficrespl,"#Age ");
                   12524:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12525:   fprintf(ficrespl,"\n");
1.180     brouard  12526:   
1.219     brouard  12527:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12528: 
1.219     brouard  12529:   agebase=ageminpar;
                   12530:   agelim=agemaxpar;
1.180     brouard  12531: 
1.227     brouard  12532:   /* i1=pow(2,ncoveff); */
1.234     brouard  12533:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12534:   if (cptcovn < 1){i1=1;}
1.180     brouard  12535: 
1.337     brouard  12536:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12537:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12538:       k=TKresult[nres];
1.338     brouard  12539:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12540:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12541:       /*       continue; */
1.235     brouard  12542: 
1.238     brouard  12543:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12544:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12545:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12546:       /* k=k+1; */
                   12547:       /* to clean */
1.332     brouard  12548:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12549:       fprintf(ficrespl,"#******");
                   12550:       printf("#******");
                   12551:       fprintf(ficlog,"#******");
1.337     brouard  12552:       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  12553:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12554:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12555:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12556:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12557:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12558:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12559:       }
                   12560:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12561:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12562:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12563:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12564:       /* } */
1.238     brouard  12565:       fprintf(ficrespl,"******\n");
                   12566:       printf("******\n");
                   12567:       fprintf(ficlog,"******\n");
                   12568:       if(invalidvarcomb[k]){
                   12569:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12570:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12571:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12572:        continue;
                   12573:       }
1.219     brouard  12574: 
1.238     brouard  12575:       fprintf(ficrespl,"#Age ");
1.337     brouard  12576:       /* for(j=1;j<=cptcoveff;j++) { */
                   12577:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12578:       /* } */
                   12579:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12580:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12581:       }
                   12582:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12583:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12584:     
1.238     brouard  12585:       for (age=agebase; age<=agelim; age++){
                   12586:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12587:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12588:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12589:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12590:        /* for(j=1;j<=cptcoveff;j++) */
                   12591:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12592:        for(j=1;j<=cptcovs;j++)
                   12593:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12594:        tot=0.;
                   12595:        for(i=1; i<=nlstate;i++){
                   12596:          tot +=  prlim[i][i];
                   12597:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12598:        }
                   12599:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12600:       } /* Age */
                   12601:       /* was end of cptcod */
1.337     brouard  12602:     } /* nres */
                   12603:   /* } /\* for each combination *\/ */
1.219     brouard  12604:   return 0;
1.180     brouard  12605: }
                   12606: 
1.218     brouard  12607: 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  12608:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12609:        
                   12610:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12611:    * at any age between ageminpar and agemaxpar
                   12612:         */
1.235     brouard  12613:   int i, j, k, i1, nres=0 ;
1.217     brouard  12614:   /* double ftolpl = 1.e-10; */
                   12615:   double age, agebase, agelim;
                   12616:   double tot;
1.218     brouard  12617:   /* double ***mobaverage; */
                   12618:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12619: 
                   12620:   strcpy(fileresplb,"PLB_");
                   12621:   strcat(fileresplb,fileresu);
                   12622:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12623:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12624:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12625:   }
1.288     brouard  12626:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12627:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12628:   pstamp(ficresplb);
1.288     brouard  12629:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12630:   fprintf(ficresplb,"#Age ");
                   12631:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12632:   fprintf(ficresplb,"\n");
                   12633:   
1.218     brouard  12634:   
                   12635:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12636:   
                   12637:   agebase=ageminpar;
                   12638:   agelim=agemaxpar;
                   12639:   
                   12640:   
1.227     brouard  12641:   i1=pow(2,cptcoveff);
1.218     brouard  12642:   if (cptcovn < 1){i1=1;}
1.227     brouard  12643:   
1.238     brouard  12644:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12645:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12646:       k=TKresult[nres];
                   12647:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12648:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12649:      /*        continue; */
                   12650:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12651:       fprintf(ficresplb,"#******");
                   12652:       printf("#******");
                   12653:       fprintf(ficlog,"#******");
1.338     brouard  12654:       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) */
                   12655:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12656:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12657:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12658:       }
1.338     brouard  12659:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12660:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12661:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12662:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12663:       /* } */
                   12664:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12665:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12666:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12667:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12668:       /* } */
1.238     brouard  12669:       fprintf(ficresplb,"******\n");
                   12670:       printf("******\n");
                   12671:       fprintf(ficlog,"******\n");
                   12672:       if(invalidvarcomb[k]){
                   12673:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12674:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12675:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12676:        continue;
                   12677:       }
1.218     brouard  12678:     
1.238     brouard  12679:       fprintf(ficresplb,"#Age ");
1.338     brouard  12680:       for(j=1;j<=cptcovs;j++) {
                   12681:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12682:       }
                   12683:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12684:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12685:     
                   12686:     
1.238     brouard  12687:       for (age=agebase; age<=agelim; age++){
                   12688:        /* for (age=agebase; age<=agebase; age++){ */
                   12689:        if(mobilavproj > 0){
                   12690:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12691:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12692:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12693:        }else if (mobilavproj == 0){
                   12694:          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);
                   12695:          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);
                   12696:          exit(1);
                   12697:        }else{
                   12698:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12699:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12700:          /* printf("TOTOT\n"); */
                   12701:           /* exit(1); */
1.238     brouard  12702:        }
                   12703:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12704:        for(j=1;j<=cptcovs;j++)
                   12705:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12706:        tot=0.;
                   12707:        for(i=1; i<=nlstate;i++){
                   12708:          tot +=  bprlim[i][i];
                   12709:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12710:        }
                   12711:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12712:       } /* Age */
                   12713:       /* was end of cptcod */
1.255     brouard  12714:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12715:     /* } /\* end of any combination *\/ */
1.238     brouard  12716:   } /* end of nres */  
1.218     brouard  12717:   /* hBijx(p, bage, fage); */
                   12718:   /* fclose(ficrespijb); */
                   12719:   
                   12720:   return 0;
1.217     brouard  12721: }
1.218     brouard  12722:  
1.180     brouard  12723: int hPijx(double *p, int bage, int fage){
                   12724:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12725:   /* to be optimized with precov */
1.180     brouard  12726:   int stepsize;
                   12727:   int agelim;
                   12728:   int hstepm;
                   12729:   int nhstepm;
1.235     brouard  12730:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12731: 
                   12732:   double agedeb;
                   12733:   double ***p3mat;
                   12734: 
1.337     brouard  12735:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12736:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12737:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12738:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12739:   }
                   12740:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12741:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12742:   
                   12743:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12744:   /*if (stepm<=24) stepsize=2;*/
                   12745:   
                   12746:   agelim=AGESUP;
                   12747:   hstepm=stepsize*YEARM; /* Every year of age */
                   12748:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12749:   
                   12750:   /* hstepm=1;   aff par mois*/
                   12751:   pstamp(ficrespij);
                   12752:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12753:   i1= pow(2,cptcoveff);
                   12754:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12755:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12756:   /*   k=k+1;  */
                   12757:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12758:     k=TKresult[nres];
1.338     brouard  12759:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12760:     /* for(k=1; k<=i1;k++){ */
                   12761:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12762:     /*         continue; */
                   12763:     fprintf(ficrespij,"\n#****** ");
                   12764:     for(j=1;j<=cptcovs;j++){
                   12765:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12766:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12767:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12768:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12769:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12770:     }
                   12771:     fprintf(ficrespij,"******\n");
                   12772:     
                   12773:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12774:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12775:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12776:       
                   12777:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12778:       
                   12779:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12780:       oldm=oldms;savm=savms;
                   12781:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12782:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12783:       for(i=1; i<=nlstate;i++)
                   12784:        for(j=1; j<=nlstate+ndeath;j++)
                   12785:          fprintf(ficrespij," %1d-%1d",i,j);
                   12786:       fprintf(ficrespij,"\n");
                   12787:       for (h=0; h<=nhstepm; h++){
                   12788:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12789:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12790:        for(i=1; i<=nlstate;i++)
                   12791:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12792:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12793:        fprintf(ficrespij,"\n");
                   12794:       }
1.337     brouard  12795:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12796:       fprintf(ficrespij,"\n");
1.180     brouard  12797:     }
1.337     brouard  12798:   }
                   12799:   /*}*/
                   12800:   return 0;
1.180     brouard  12801: }
1.218     brouard  12802:  
                   12803:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12804:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12805:     /* To be optimized with precov */
1.217     brouard  12806:   int stepsize;
1.218     brouard  12807:   /* int agelim; */
                   12808:        int ageminl;
1.217     brouard  12809:   int hstepm;
                   12810:   int nhstepm;
1.238     brouard  12811:   int h, i, i1, j, k, nres;
1.218     brouard  12812:        
1.217     brouard  12813:   double agedeb;
                   12814:   double ***p3mat;
1.218     brouard  12815:        
                   12816:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12817:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12818:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12819:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12820:   }
                   12821:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12822:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12823:   
                   12824:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12825:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12826:   
1.218     brouard  12827:   /* agelim=AGESUP; */
1.289     brouard  12828:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12829:   hstepm=stepsize*YEARM; /* Every year of age */
                   12830:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12831:   
                   12832:   /* hstepm=1;   aff par mois*/
                   12833:   pstamp(ficrespijb);
1.255     brouard  12834:   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  12835:   i1= pow(2,cptcoveff);
1.218     brouard  12836:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12837:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12838:   /*   k=k+1;  */
1.238     brouard  12839:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12840:     k=TKresult[nres];
1.338     brouard  12841:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12842:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12843:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12844:     /*         continue; */
                   12845:     fprintf(ficrespijb,"\n#****** ");
                   12846:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12847:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12848:       /* for(j=1;j<=cptcoveff;j++) */
                   12849:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12850:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12851:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12852:     }
                   12853:     fprintf(ficrespijb,"******\n");
                   12854:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12855:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12856:       continue;
                   12857:     }
                   12858:     
                   12859:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12860:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12861:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12862:       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 */
                   12863:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12864:       
                   12865:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12866:       
                   12867:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12868:       /* and memory limitations if stepm is small */
                   12869:       
                   12870:       /* oldm=oldms;savm=savms; */
                   12871:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12872:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12873:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12874:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12875:       for(i=1; i<=nlstate;i++)
                   12876:        for(j=1; j<=nlstate+ndeath;j++)
                   12877:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12878:       fprintf(ficrespijb,"\n");
                   12879:       for (h=0; h<=nhstepm; h++){
                   12880:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12881:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12882:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12883:        for(i=1; i<=nlstate;i++)
                   12884:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12885:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12886:        fprintf(ficrespijb,"\n");
1.337     brouard  12887:       }
                   12888:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12889:       fprintf(ficrespijb,"\n");
                   12890:     } /* end age deb */
                   12891:     /* } /\* end combination *\/ */
1.238     brouard  12892:   } /* end nres */
1.218     brouard  12893:   return 0;
                   12894:  } /*  hBijx */
1.217     brouard  12895: 
1.180     brouard  12896: 
1.136     brouard  12897: /***********************************************/
                   12898: /**************** Main Program *****************/
                   12899: /***********************************************/
                   12900: 
                   12901: int main(int argc, char *argv[])
                   12902: {
                   12903: #ifdef GSL
                   12904:   const gsl_multimin_fminimizer_type *T;
                   12905:   size_t iteri = 0, it;
                   12906:   int rval = GSL_CONTINUE;
                   12907:   int status = GSL_SUCCESS;
                   12908:   double ssval;
                   12909: #endif
                   12910:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12911:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12912:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12913:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12914:   int jj, ll, li, lj, lk;
1.136     brouard  12915:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12916:   int num_filled;
1.136     brouard  12917:   int itimes;
                   12918:   int NDIM=2;
                   12919:   int vpopbased=0;
1.235     brouard  12920:   int nres=0;
1.258     brouard  12921:   int endishere=0;
1.277     brouard  12922:   int noffset=0;
1.274     brouard  12923:   int ncurrv=0; /* Temporary variable */
                   12924:   
1.164     brouard  12925:   char ca[32], cb[32];
1.136     brouard  12926:   /*  FILE *fichtm; *//* Html File */
                   12927:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12928:   struct stat info;
1.191     brouard  12929:   double agedeb=0.;
1.194     brouard  12930: 
                   12931:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12932:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12933: 
1.165     brouard  12934:   double fret;
1.191     brouard  12935:   double dum=0.; /* Dummy variable */
1.136     brouard  12936:   double ***p3mat;
1.218     brouard  12937:   /* double ***mobaverage; */
1.319     brouard  12938:   double wald;
1.164     brouard  12939: 
                   12940:   char line[MAXLINE];
1.197     brouard  12941:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12942: 
1.234     brouard  12943:   char  modeltemp[MAXLINE];
1.332     brouard  12944:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12945:   
1.136     brouard  12946:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12947:   char *tok, *val; /* pathtot */
1.334     brouard  12948:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12949:   int c,  h , cpt, c2;
1.191     brouard  12950:   int jl=0;
                   12951:   int i1, j1, jk, stepsize=0;
1.194     brouard  12952:   int count=0;
                   12953: 
1.164     brouard  12954:   int *tab; 
1.136     brouard  12955:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12956:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12957:   /* double anprojf, mprojf, jprojf; */
                   12958:   /* double jintmean,mintmean,aintmean;   */
                   12959:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12960:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12961:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12962:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12963:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12964:   int mobilav=0,popforecast=0;
1.191     brouard  12965:   int hstepm=0, nhstepm=0;
1.136     brouard  12966:   int agemortsup;
                   12967:   float  sumlpop=0.;
                   12968:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12969:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12970: 
1.191     brouard  12971:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12972:   double ftolpl=FTOL;
                   12973:   double **prlim;
1.217     brouard  12974:   double **bprlim;
1.317     brouard  12975:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12976:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12977:   double ***paramstart; /* Matrix of starting parameter values */
                   12978:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12979:   double **matcov; /* Matrix of covariance */
1.203     brouard  12980:   double **hess; /* Hessian matrix */
1.136     brouard  12981:   double ***delti3; /* Scale */
                   12982:   double *delti; /* Scale */
                   12983:   double ***eij, ***vareij;
                   12984:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12985: 
1.136     brouard  12986:   double *epj, vepp;
1.164     brouard  12987: 
1.273     brouard  12988:   double dateprev1, dateprev2;
1.296     brouard  12989:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12990:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12991: 
1.217     brouard  12992: 
1.136     brouard  12993:   double **ximort;
1.145     brouard  12994:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12995:   int *dcwave;
                   12996: 
1.164     brouard  12997:   char z[1]="c";
1.136     brouard  12998: 
                   12999:   /*char  *strt;*/
                   13000:   char strtend[80];
1.126     brouard  13001: 
1.164     brouard  13002: 
1.126     brouard  13003: /*   setlocale (LC_ALL, ""); */
                   13004: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13005: /*   textdomain (PACKAGE); */
                   13006: /*   setlocale (LC_CTYPE, ""); */
                   13007: /*   setlocale (LC_MESSAGES, ""); */
                   13008: 
                   13009:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13010:   rstart_time = time(NULL);  
                   13011:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13012:   start_time = *localtime(&rstart_time);
1.126     brouard  13013:   curr_time=start_time;
1.157     brouard  13014:   /*tml = *localtime(&start_time.tm_sec);*/
                   13015:   /* strcpy(strstart,asctime(&tml)); */
                   13016:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13017: 
                   13018: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13019: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13020: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13021: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13022: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13023: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13024: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13025: /*   strt=asctime(&tmg); */
                   13026: /*   printf("Time(after) =%s",strstart);  */
                   13027: /*  (void) time (&time_value);
                   13028: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13029: *  tm = *localtime(&time_value);
                   13030: *  strstart=asctime(&tm);
                   13031: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13032: */
                   13033: 
                   13034:   nberr=0; /* Number of errors and warnings */
                   13035:   nbwarn=0;
1.184     brouard  13036: #ifdef WIN32
                   13037:   _getcwd(pathcd, size);
                   13038: #else
1.126     brouard  13039:   getcwd(pathcd, size);
1.184     brouard  13040: #endif
1.191     brouard  13041:   syscompilerinfo(0);
1.196     brouard  13042:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13043:   if(argc <=1){
                   13044:     printf("\nEnter the parameter file name: ");
1.205     brouard  13045:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13046:       printf("ERROR Empty parameter file name\n");
                   13047:       goto end;
                   13048:     }
1.126     brouard  13049:     i=strlen(pathr);
                   13050:     if(pathr[i-1]=='\n')
                   13051:       pathr[i-1]='\0';
1.156     brouard  13052:     i=strlen(pathr);
1.205     brouard  13053:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13054:       pathr[i-1]='\0';
1.205     brouard  13055:     }
                   13056:     i=strlen(pathr);
                   13057:     if( i==0 ){
                   13058:       printf("ERROR Empty parameter file name\n");
                   13059:       goto end;
                   13060:     }
                   13061:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13062:       printf("Pathr |%s|\n",pathr);
                   13063:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13064:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13065:       strcpy (pathtot, val);
                   13066:       if(pathr[0] == '\0') break; /* Dirty */
                   13067:     }
                   13068:   }
1.281     brouard  13069:   else if (argc<=2){
                   13070:     strcpy(pathtot,argv[1]);
                   13071:   }
1.126     brouard  13072:   else{
                   13073:     strcpy(pathtot,argv[1]);
1.281     brouard  13074:     strcpy(z,argv[2]);
                   13075:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13076:   }
                   13077:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13078:   /*cygwin_split_path(pathtot,path,optionfile);
                   13079:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13080:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13081: 
                   13082:   /* Split argv[0], imach program to get pathimach */
                   13083:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13084:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13085:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13086:  /*   strcpy(pathimach,argv[0]); */
                   13087:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13088:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13089:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13090: #ifdef WIN32
                   13091:   _chdir(path); /* Can be a relative path */
                   13092:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13093: #else
1.126     brouard  13094:   chdir(path); /* Can be a relative path */
1.184     brouard  13095:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13096: #endif
                   13097:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13098:   strcpy(command,"mkdir ");
                   13099:   strcat(command,optionfilefiname);
                   13100:   if((outcmd=system(command)) != 0){
1.169     brouard  13101:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13102:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13103:     /* fclose(ficlog); */
                   13104: /*     exit(1); */
                   13105:   }
                   13106: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13107: /*     perror("mkdir"); */
                   13108: /*   } */
                   13109: 
                   13110:   /*-------- arguments in the command line --------*/
                   13111: 
1.186     brouard  13112:   /* Main Log file */
1.126     brouard  13113:   strcat(filelog, optionfilefiname);
                   13114:   strcat(filelog,".log");    /* */
                   13115:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13116:     printf("Problem with logfile %s\n",filelog);
                   13117:     goto end;
                   13118:   }
                   13119:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13120:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13121:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13122:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13123:  path=%s \n\
                   13124:  optionfile=%s\n\
                   13125:  optionfilext=%s\n\
1.156     brouard  13126:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13127: 
1.197     brouard  13128:   syscompilerinfo(1);
1.167     brouard  13129: 
1.126     brouard  13130:   printf("Local time (at start):%s",strstart);
                   13131:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13132:   fflush(ficlog);
                   13133: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13134: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13135: 
                   13136:   /* */
                   13137:   strcpy(fileres,"r");
                   13138:   strcat(fileres, optionfilefiname);
1.201     brouard  13139:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13140:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13141:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13142: 
1.186     brouard  13143:   /* Main ---------arguments file --------*/
1.126     brouard  13144: 
                   13145:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13146:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13147:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13148:     fflush(ficlog);
1.149     brouard  13149:     /* goto end; */
                   13150:     exit(70); 
1.126     brouard  13151:   }
                   13152: 
                   13153:   strcpy(filereso,"o");
1.201     brouard  13154:   strcat(filereso,fileresu);
1.126     brouard  13155:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13156:     printf("Problem with Output resultfile: %s\n", filereso);
                   13157:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13158:     fflush(ficlog);
                   13159:     goto end;
                   13160:   }
1.278     brouard  13161:       /*-------- Rewriting parameter file ----------*/
                   13162:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13163:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13164:   strcat(rfileres,".");    /* */
                   13165:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13166:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13167:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13168:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13169:     fflush(ficlog);
                   13170:     goto end;
                   13171:   }
                   13172:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13173: 
1.278     brouard  13174:                                      
1.126     brouard  13175:   /* Reads comments: lines beginning with '#' */
                   13176:   numlinepar=0;
1.277     brouard  13177:   /* Is it a BOM UTF-8 Windows file? */
                   13178:   /* First parameter line */
1.197     brouard  13179:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13180:     noffset=0;
                   13181:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13182:     {
                   13183:       noffset=noffset+3;
                   13184:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13185:     }
1.302     brouard  13186: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13187:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13188:     {
                   13189:       noffset=noffset+2;
                   13190:       printf("# File is an UTF16BE BOM file\n");
                   13191:     }
                   13192:     else if( line[0] == 0 && line[1] == 0)
                   13193:     {
                   13194:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13195:        noffset=noffset+4;
                   13196:        printf("# File is an UTF16BE BOM file\n");
                   13197:       }
                   13198:     } else{
                   13199:       ;/*printf(" Not a BOM file\n");*/
                   13200:     }
                   13201:   
1.197     brouard  13202:     /* If line starts with a # it is a comment */
1.277     brouard  13203:     if (line[noffset] == '#') {
1.197     brouard  13204:       numlinepar++;
                   13205:       fputs(line,stdout);
                   13206:       fputs(line,ficparo);
1.278     brouard  13207:       fputs(line,ficres);
1.197     brouard  13208:       fputs(line,ficlog);
                   13209:       continue;
                   13210:     }else
                   13211:       break;
                   13212:   }
                   13213:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13214:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13215:     if (num_filled != 5) {
                   13216:       printf("Should be 5 parameters\n");
1.283     brouard  13217:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13218:     }
1.126     brouard  13219:     numlinepar++;
1.197     brouard  13220:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13221:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13222:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13223:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13224:   }
                   13225:   /* Second parameter line */
                   13226:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13227:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13228:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13229:     if (line[0] == '#') {
                   13230:       numlinepar++;
1.283     brouard  13231:       printf("%s",line);
                   13232:       fprintf(ficres,"%s",line);
                   13233:       fprintf(ficparo,"%s",line);
                   13234:       fprintf(ficlog,"%s",line);
1.197     brouard  13235:       continue;
                   13236:     }else
                   13237:       break;
                   13238:   }
1.223     brouard  13239:   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", \
                   13240:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13241:     if (num_filled != 11) {
                   13242:       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  13243:       printf("but line=%s\n",line);
1.283     brouard  13244:       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");
                   13245:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13246:     }
1.286     brouard  13247:     if( lastpass > maxwav){
                   13248:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13249:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13250:       fflush(ficlog);
                   13251:       goto end;
                   13252:     }
                   13253:       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  13254:     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  13255:     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  13256:     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  13257:   }
1.203     brouard  13258:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13259:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13260:   /* Third parameter line */
                   13261:   while(fgets(line, MAXLINE, ficpar)) {
                   13262:     /* If line starts with a # it is a comment */
                   13263:     if (line[0] == '#') {
                   13264:       numlinepar++;
1.283     brouard  13265:       printf("%s",line);
                   13266:       fprintf(ficres,"%s",line);
                   13267:       fprintf(ficparo,"%s",line);
                   13268:       fprintf(ficlog,"%s",line);
1.197     brouard  13269:       continue;
                   13270:     }else
                   13271:       break;
                   13272:   }
1.201     brouard  13273:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  13274:     if (num_filled != 1){
1.302     brouard  13275:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13276:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13277:       model[0]='\0';
                   13278:       goto end;
                   13279:     }
                   13280:     else{
                   13281:       if (model[0]=='+'){
                   13282:        for(i=1; i<=strlen(model);i++)
                   13283:          modeltemp[i-1]=model[i];
1.201     brouard  13284:        strcpy(model,modeltemp); 
1.197     brouard  13285:       }
                   13286:     }
1.338     brouard  13287:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13288:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13289:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13290:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13291:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13292:   }
                   13293:   /* 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); */
                   13294:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13295:   /* 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  13296:   /* 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); */
                   13297:   /* 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  13298:   fflush(ficlog);
1.190     brouard  13299:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13300:   if(model[0]=='#'){
1.279     brouard  13301:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13302:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13303:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13304:     if(mle != -1){
1.279     brouard  13305:       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  13306:       exit(1);
                   13307:     }
                   13308:   }
1.126     brouard  13309:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13310:     ungetc(c,ficpar);
                   13311:     fgets(line, MAXLINE, ficpar);
                   13312:     numlinepar++;
1.195     brouard  13313:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13314:       z[0]=line[1];
1.342     brouard  13315:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13316:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13317:     }
                   13318:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13319:     fputs(line, stdout);
                   13320:     //puts(line);
1.126     brouard  13321:     fputs(line,ficparo);
                   13322:     fputs(line,ficlog);
                   13323:   }
                   13324:   ungetc(c,ficpar);
                   13325: 
                   13326:    
1.290     brouard  13327:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13328:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13329:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13330:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13331:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13332:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13333:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13334:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13335:   */
                   13336:   if (strlen(model)>1) 
1.187     brouard  13337:     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  13338:   else
1.187     brouard  13339:     ncovmodel=2; /* Constant and age */
1.133     brouard  13340:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13341:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13342:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13343:     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);
                   13344:     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);
                   13345:     fflush(stdout);
                   13346:     fclose (ficlog);
                   13347:     goto end;
                   13348:   }
1.126     brouard  13349:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13350:   delti=delti3[1][1];
                   13351:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13352:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13353: /* We could also provide initial parameters values giving by simple logistic regression 
                   13354:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13355:       /* for(i=1;i<nlstate;i++){ */
                   13356:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13357:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13358:       /* } */
1.126     brouard  13359:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13360:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13361:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13362:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13363:     fclose (ficparo);
                   13364:     fclose (ficlog);
                   13365:     goto end;
                   13366:     exit(0);
1.220     brouard  13367:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13368:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13369:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13370:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13371:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13372:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13373:     hess=matrix(1,npar,1,npar);
1.220     brouard  13374:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13375:     /* Read guessed parameters */
1.126     brouard  13376:     /* Reads comments: lines beginning with '#' */
                   13377:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13378:       ungetc(c,ficpar);
                   13379:       fgets(line, MAXLINE, ficpar);
                   13380:       numlinepar++;
1.141     brouard  13381:       fputs(line,stdout);
1.126     brouard  13382:       fputs(line,ficparo);
                   13383:       fputs(line,ficlog);
                   13384:     }
                   13385:     ungetc(c,ficpar);
                   13386:     
                   13387:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13388:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13389:     for(i=1; i <=nlstate; i++){
1.234     brouard  13390:       j=0;
1.126     brouard  13391:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13392:        if(jj==i) continue;
                   13393:        j++;
1.292     brouard  13394:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13395:          ungetc(c,ficpar);
                   13396:          fgets(line, MAXLINE, ficpar);
                   13397:          numlinepar++;
                   13398:          fputs(line,stdout);
                   13399:          fputs(line,ficparo);
                   13400:          fputs(line,ficlog);
                   13401:        }
                   13402:        ungetc(c,ficpar);
1.234     brouard  13403:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13404:        if ((i1 != i) || (j1 != jj)){
                   13405:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13406: It might be a problem of design; if ncovcol and the model are correct\n \
                   13407: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13408:          exit(1);
                   13409:        }
                   13410:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13411:        if(mle==1)
                   13412:          printf("%1d%1d",i,jj);
                   13413:        fprintf(ficlog,"%1d%1d",i,jj);
                   13414:        for(k=1; k<=ncovmodel;k++){
                   13415:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13416:          if(mle==1){
                   13417:            printf(" %lf",param[i][j][k]);
                   13418:            fprintf(ficlog," %lf",param[i][j][k]);
                   13419:          }
                   13420:          else
                   13421:            fprintf(ficlog," %lf",param[i][j][k]);
                   13422:          fprintf(ficparo," %lf",param[i][j][k]);
                   13423:        }
                   13424:        fscanf(ficpar,"\n");
                   13425:        numlinepar++;
                   13426:        if(mle==1)
                   13427:          printf("\n");
                   13428:        fprintf(ficlog,"\n");
                   13429:        fprintf(ficparo,"\n");
1.126     brouard  13430:       }
                   13431:     }  
                   13432:     fflush(ficlog);
1.234     brouard  13433:     
1.251     brouard  13434:     /* Reads parameters values */
1.126     brouard  13435:     p=param[1][1];
1.251     brouard  13436:     pstart=paramstart[1][1];
1.126     brouard  13437:     
                   13438:     /* Reads comments: lines beginning with '#' */
                   13439:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13440:       ungetc(c,ficpar);
                   13441:       fgets(line, MAXLINE, ficpar);
                   13442:       numlinepar++;
1.141     brouard  13443:       fputs(line,stdout);
1.126     brouard  13444:       fputs(line,ficparo);
                   13445:       fputs(line,ficlog);
                   13446:     }
                   13447:     ungetc(c,ficpar);
                   13448: 
                   13449:     for(i=1; i <=nlstate; i++){
                   13450:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13451:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13452:        if ( (i1-i) * (j1-j) != 0){
                   13453:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13454:          exit(1);
                   13455:        }
                   13456:        printf("%1d%1d",i,j);
                   13457:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13458:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13459:        for(k=1; k<=ncovmodel;k++){
                   13460:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13461:          printf(" %le",delti3[i][j][k]);
                   13462:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13463:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13464:        }
                   13465:        fscanf(ficpar,"\n");
                   13466:        numlinepar++;
                   13467:        printf("\n");
                   13468:        fprintf(ficparo,"\n");
                   13469:        fprintf(ficlog,"\n");
1.126     brouard  13470:       }
                   13471:     }
                   13472:     fflush(ficlog);
1.234     brouard  13473:     
1.145     brouard  13474:     /* Reads covariance matrix */
1.126     brouard  13475:     delti=delti3[1][1];
1.220     brouard  13476:                
                   13477:                
1.126     brouard  13478:     /* 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  13479:                
1.126     brouard  13480:     /* Reads comments: lines beginning with '#' */
                   13481:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13482:       ungetc(c,ficpar);
                   13483:       fgets(line, MAXLINE, ficpar);
                   13484:       numlinepar++;
1.141     brouard  13485:       fputs(line,stdout);
1.126     brouard  13486:       fputs(line,ficparo);
                   13487:       fputs(line,ficlog);
                   13488:     }
                   13489:     ungetc(c,ficpar);
1.220     brouard  13490:                
1.126     brouard  13491:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13492:     hess=matrix(1,npar,1,npar);
1.131     brouard  13493:     for(i=1; i <=npar; i++)
                   13494:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13495:                
1.194     brouard  13496:     /* Scans npar lines */
1.126     brouard  13497:     for(i=1; i <=npar; i++){
1.226     brouard  13498:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13499:       if(count != 3){
1.226     brouard  13500:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13501: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13502: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13503:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13504: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13505: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13506:        exit(1);
1.220     brouard  13507:       }else{
1.226     brouard  13508:        if(mle==1)
                   13509:          printf("%1d%1d%d",i1,j1,jk);
                   13510:       }
                   13511:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13512:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13513:       for(j=1; j <=i; j++){
1.226     brouard  13514:        fscanf(ficpar," %le",&matcov[i][j]);
                   13515:        if(mle==1){
                   13516:          printf(" %.5le",matcov[i][j]);
                   13517:        }
                   13518:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13519:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13520:       }
                   13521:       fscanf(ficpar,"\n");
                   13522:       numlinepar++;
                   13523:       if(mle==1)
1.220     brouard  13524:                                printf("\n");
1.126     brouard  13525:       fprintf(ficlog,"\n");
                   13526:       fprintf(ficparo,"\n");
                   13527:     }
1.194     brouard  13528:     /* End of read covariance matrix npar lines */
1.126     brouard  13529:     for(i=1; i <=npar; i++)
                   13530:       for(j=i+1;j<=npar;j++)
1.226     brouard  13531:        matcov[i][j]=matcov[j][i];
1.126     brouard  13532:     
                   13533:     if(mle==1)
                   13534:       printf("\n");
                   13535:     fprintf(ficlog,"\n");
                   13536:     
                   13537:     fflush(ficlog);
                   13538:     
                   13539:   }    /* End of mle != -3 */
1.218     brouard  13540:   
1.186     brouard  13541:   /*  Main data
                   13542:    */
1.290     brouard  13543:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13544:   /* num=lvector(1,n); */
                   13545:   /* moisnais=vector(1,n); */
                   13546:   /* annais=vector(1,n); */
                   13547:   /* moisdc=vector(1,n); */
                   13548:   /* andc=vector(1,n); */
                   13549:   /* weight=vector(1,n); */
                   13550:   /* agedc=vector(1,n); */
                   13551:   /* cod=ivector(1,n); */
                   13552:   /* for(i=1;i<=n;i++){ */
                   13553:   num=lvector(firstobs,lastobs);
                   13554:   moisnais=vector(firstobs,lastobs);
                   13555:   annais=vector(firstobs,lastobs);
                   13556:   moisdc=vector(firstobs,lastobs);
                   13557:   andc=vector(firstobs,lastobs);
                   13558:   weight=vector(firstobs,lastobs);
                   13559:   agedc=vector(firstobs,lastobs);
                   13560:   cod=ivector(firstobs,lastobs);
                   13561:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13562:     num[i]=0;
                   13563:     moisnais[i]=0;
                   13564:     annais[i]=0;
                   13565:     moisdc[i]=0;
                   13566:     andc[i]=0;
                   13567:     agedc[i]=0;
                   13568:     cod[i]=0;
                   13569:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13570:   }
1.290     brouard  13571:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13572:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13573:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13574:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13575:   tab=ivector(1,NCOVMAX);
1.144     brouard  13576:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13577:   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  13578: 
1.136     brouard  13579:   /* Reads data from file datafile */
                   13580:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13581:     goto end;
                   13582: 
                   13583:   /* Calculation of the number of parameters from char model */
1.234     brouard  13584:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13585:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13586:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13587:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13588:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13589:   */
                   13590:   
                   13591:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13592:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13593:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13594:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13595:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13596:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13597:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13598:   TvarF=ivector(1,NCOVMAX); /*  */
                   13599:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13600:   TvarV=ivector(1,NCOVMAX); /*  */
                   13601:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13602:   TvarA=ivector(1,NCOVMAX); /*  */
                   13603:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13604:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13605:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13606:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13607:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13608:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13609:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13610:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13611:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13612:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13613:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13614:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13615:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13616:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13617:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13618: 
1.230     brouard  13619:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13620:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13621:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13622:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13623:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13624:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13625:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13626: 
1.137     brouard  13627:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13628:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13629:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13630:   */
                   13631:   /* For model-covariate k tells which data-covariate to use but
                   13632:     because this model-covariate is a construction we invent a new column
                   13633:     ncovcol + k1
                   13634:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13635:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13636:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13637:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13638:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13639:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13640:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13641:   */
1.145     brouard  13642:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13643:   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  13644:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13645:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.349     brouard  13646:   Tvardk=imatrix(-1,NCOVMAX,1,2);
1.145     brouard  13647:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13648:                         4 covariates (3 plus signs)
                   13649:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13650:                           */  
                   13651:   for(i=1;i<NCOVMAX;i++)
                   13652:     Tage[i]=0;
1.230     brouard  13653:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13654:                                * individual dummy, fixed or varying:
                   13655:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13656:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13657:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13658:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13659:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13660:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13661:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13662:                                * individual quantitative, fixed or varying:
                   13663:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13664:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13665:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13666: 
                   13667: /* Probably useless zeroes */
                   13668:   for(i=1;i<NCOVMAX;i++){
                   13669:     DummyV[i]=0;
                   13670:     FixedV[i]=0;
                   13671:   }
                   13672: 
                   13673:   for(i=1; i <=ncovcol;i++){
                   13674:     DummyV[i]=0;
                   13675:     FixedV[i]=0;
                   13676:   }
                   13677:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13678:     DummyV[i]=1;
                   13679:     FixedV[i]=0;
                   13680:   }
                   13681:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13682:     DummyV[i]=0;
                   13683:     FixedV[i]=1;
                   13684:   }
                   13685:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13686:     DummyV[i]=1;
                   13687:     FixedV[i]=1;
                   13688:   }
                   13689:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13690:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13691:     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]);
                   13692:   }
                   13693: 
                   13694: 
                   13695: 
1.186     brouard  13696: /* Main decodemodel */
                   13697: 
1.187     brouard  13698: 
1.223     brouard  13699:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13700:     goto end;
                   13701: 
1.137     brouard  13702:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13703:     nbwarn++;
                   13704:     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); 
                   13705:     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); 
                   13706:   }
1.136     brouard  13707:     /*  if(mle==1){*/
1.137     brouard  13708:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13709:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13710:   }
                   13711: 
                   13712:     /*-calculation of age at interview from date of interview and age at death -*/
                   13713:   agev=matrix(1,maxwav,1,imx);
                   13714: 
                   13715:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13716:     goto end;
                   13717: 
1.126     brouard  13718: 
1.136     brouard  13719:   agegomp=(int)agemin;
1.290     brouard  13720:   free_vector(moisnais,firstobs,lastobs);
                   13721:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13722:   /* free_matrix(mint,1,maxwav,1,n);
                   13723:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13724:   /* free_vector(moisdc,1,n); */
                   13725:   /* free_vector(andc,1,n); */
1.145     brouard  13726:   /* */
                   13727:   
1.126     brouard  13728:   wav=ivector(1,imx);
1.214     brouard  13729:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13730:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13731:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13732:   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.*/
                   13733:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13734:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13735:    
                   13736:   /* Concatenates waves */
1.214     brouard  13737:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13738:      Death is a valid wave (if date is known).
                   13739:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13740:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13741:      and mw[mi+1][i]. dh depends on stepm.
                   13742:   */
                   13743: 
1.126     brouard  13744:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13745:   /* Concatenates waves */
1.145     brouard  13746:  
1.290     brouard  13747:   free_vector(moisdc,firstobs,lastobs);
                   13748:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13749: 
1.126     brouard  13750:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13751:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13752:   ncodemax[1]=1;
1.145     brouard  13753:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13754:   cptcoveff=0;
1.220     brouard  13755:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13756:     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  13757:   }
                   13758:   
                   13759:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13760:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13761:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13762:     invalidvarcomb[i]=0;
                   13763:   
1.211     brouard  13764:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13765:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13766:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13767:   
1.200     brouard  13768:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13769:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13770:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13771:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13772:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13773:    * (currently 0 or 1) in the data.
                   13774:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13775:    * corresponding modality (h,j).
                   13776:    */
                   13777: 
1.145     brouard  13778:   h=0;
                   13779:   /*if (cptcovn > 0) */
1.126     brouard  13780:   m=pow(2,cptcoveff);
                   13781:  
1.144     brouard  13782:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13783:           * For k=4 covariates, h goes from 1 to m=2**k
                   13784:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13785:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13786:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13787:           *______________________________   *______________________
                   13788:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13789:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13790:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13791:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13792:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13793:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13794:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13795:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13796:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13797:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13798:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13799:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13800:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13801:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13802:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13803:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13804:           */                                     
1.212     brouard  13805:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13806:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13807:      * and the value of each covariate?
                   13808:      * V1=1, V2=1, V3=2, V4=1 ?
                   13809:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13810:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13811:      * In order to get the real value in the data, we use nbcode
                   13812:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13813:      * We are keeping this crazy system in order to be able (in the future?) 
                   13814:      * to have more than 2 values (0 or 1) for a covariate.
                   13815:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13816:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13817:      *              bbbbbbbb
                   13818:      *              76543210     
                   13819:      *   h-1        00000101 (6-1=5)
1.219     brouard  13820:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13821:      *           &
                   13822:      *     1        00000001 (1)
1.219     brouard  13823:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13824:      *          +1= 00000001 =1 
1.211     brouard  13825:      *
                   13826:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13827:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13828:      *    >>k'            11
                   13829:      *          &   00000001
                   13830:      *            = 00000001
                   13831:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13832:      * Reverse h=6 and m=16?
                   13833:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13834:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13835:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13836:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13837:      * V3=decodtabm(14,3,2**4)=2
                   13838:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13839:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13840:      *          &1 000000001
                   13841:      *           = 000000001
                   13842:      *         +1= 000000010 =2
                   13843:      *                  2211
                   13844:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13845:      *                  V3=2
1.220     brouard  13846:                 * codtabm and decodtabm are identical
1.211     brouard  13847:      */
                   13848: 
1.145     brouard  13849: 
                   13850:  free_ivector(Ndum,-1,NCOVMAX);
                   13851: 
                   13852: 
1.126     brouard  13853:     
1.186     brouard  13854:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13855:   strcpy(optionfilegnuplot,optionfilefiname);
                   13856:   if(mle==-3)
1.201     brouard  13857:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13858:   strcat(optionfilegnuplot,".gp");
                   13859: 
                   13860:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13861:     printf("Problem with file %s",optionfilegnuplot);
                   13862:   }
                   13863:   else{
1.204     brouard  13864:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13865:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13866:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13867:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13868:   }
                   13869:   /*  fclose(ficgp);*/
1.186     brouard  13870: 
                   13871: 
                   13872:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13873: 
                   13874:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13875:   if(mle==-3)
1.201     brouard  13876:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13877:   strcat(optionfilehtm,".htm");
                   13878:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13879:     printf("Problem with %s \n",optionfilehtm);
                   13880:     exit(0);
1.126     brouard  13881:   }
                   13882: 
                   13883:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13884:   strcat(optionfilehtmcov,"-cov.htm");
                   13885:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13886:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13887:   }
                   13888:   else{
                   13889:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13890: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13891: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13892:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13893:   }
                   13894: 
1.335     brouard  13895:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13896: <title>IMaCh %s</title></head>\n\
                   13897:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13898: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13899: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13900: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13901: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13902:   
                   13903:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13904: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13905: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13906: 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  13907: \n\
                   13908: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13909:  <ul><li><h4>Parameter files</h4>\n\
                   13910:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13911:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13912:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13913:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13914:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13915:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13916:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13917:          fileres,fileres,\
                   13918:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13919:   fflush(fichtm);
                   13920: 
                   13921:   strcpy(pathr,path);
                   13922:   strcat(pathr,optionfilefiname);
1.184     brouard  13923: #ifdef WIN32
                   13924:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13925: #else
1.126     brouard  13926:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13927: #endif
                   13928:          
1.126     brouard  13929:   
1.220     brouard  13930:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13931:                 and for any valid combination of covariates
1.126     brouard  13932:      and prints on file fileres'p'. */
1.251     brouard  13933:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13934:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13935: 
                   13936:   fprintf(fichtm,"\n");
1.286     brouard  13937:   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  13938:          ftol, stepm);
                   13939:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13940:   ncurrv=1;
                   13941:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13942:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13943:   ncurrv=i;
                   13944:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13945:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13946:   ncurrv=i;
                   13947:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13948:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13949:   ncurrv=i;
                   13950:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13951:   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", \
                   13952:           nlstate, ndeath, maxwav, mle, weightopt);
                   13953: 
                   13954:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13955: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13956: 
                   13957:   
1.317     brouard  13958:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13959: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13960: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13961:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13962:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13963:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13964:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13965:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13966:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13967: 
1.126     brouard  13968:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13969:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13970:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13971: 
                   13972:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13973:   /* For mortality only */
1.126     brouard  13974:   if (mle==-3){
1.136     brouard  13975:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13976:     for(i=1;i<=NDIM;i++)
                   13977:       for(j=1;j<=NDIM;j++)
                   13978:        ximort[i][j]=0.;
1.186     brouard  13979:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13980:     cens=ivector(firstobs,lastobs);
                   13981:     ageexmed=vector(firstobs,lastobs);
                   13982:     agecens=vector(firstobs,lastobs);
                   13983:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13984:                
1.126     brouard  13985:     for (i=1; i<=imx; i++){
                   13986:       dcwave[i]=-1;
                   13987:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13988:        if (s[m][i]>nlstate) {
                   13989:          dcwave[i]=m;
                   13990:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13991:          break;
                   13992:        }
1.126     brouard  13993:     }
1.226     brouard  13994:     
1.126     brouard  13995:     for (i=1; i<=imx; i++) {
                   13996:       if (wav[i]>0){
1.226     brouard  13997:        ageexmed[i]=agev[mw[1][i]][i];
                   13998:        j=wav[i];
                   13999:        agecens[i]=1.; 
                   14000:        
                   14001:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14002:          agecens[i]=agev[mw[j][i]][i];
                   14003:          cens[i]= 1;
                   14004:        }else if (ageexmed[i]< 1) 
                   14005:          cens[i]= -1;
                   14006:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14007:          cens[i]=0 ;
1.126     brouard  14008:       }
                   14009:       else cens[i]=-1;
                   14010:     }
                   14011:     
                   14012:     for (i=1;i<=NDIM;i++) {
                   14013:       for (j=1;j<=NDIM;j++)
1.226     brouard  14014:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14015:     }
                   14016:     
1.302     brouard  14017:     p[1]=0.0268; p[NDIM]=0.083;
                   14018:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14019:     
                   14020:     
1.136     brouard  14021: #ifdef GSL
                   14022:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14023: #else
1.126     brouard  14024:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14025: #endif
1.201     brouard  14026:     strcpy(filerespow,"POW-MORT_"); 
                   14027:     strcat(filerespow,fileresu);
1.126     brouard  14028:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14029:       printf("Problem with resultfile: %s\n", filerespow);
                   14030:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14031:     }
1.136     brouard  14032: #ifdef GSL
                   14033:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14034: #else
1.126     brouard  14035:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14036: #endif
1.126     brouard  14037:     /*  for (i=1;i<=nlstate;i++)
                   14038:        for(j=1;j<=nlstate+ndeath;j++)
                   14039:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14040:     */
                   14041:     fprintf(ficrespow,"\n");
1.136     brouard  14042: #ifdef GSL
                   14043:     /* gsl starts here */ 
                   14044:     T = gsl_multimin_fminimizer_nmsimplex;
                   14045:     gsl_multimin_fminimizer *sfm = NULL;
                   14046:     gsl_vector *ss, *x;
                   14047:     gsl_multimin_function minex_func;
                   14048: 
                   14049:     /* Initial vertex size vector */
                   14050:     ss = gsl_vector_alloc (NDIM);
                   14051:     
                   14052:     if (ss == NULL){
                   14053:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14054:     }
                   14055:     /* Set all step sizes to 1 */
                   14056:     gsl_vector_set_all (ss, 0.001);
                   14057: 
                   14058:     /* Starting point */
1.126     brouard  14059:     
1.136     brouard  14060:     x = gsl_vector_alloc (NDIM);
                   14061:     
                   14062:     if (x == NULL){
                   14063:       gsl_vector_free(ss);
                   14064:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14065:     }
                   14066:   
                   14067:     /* Initialize method and iterate */
                   14068:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14069:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14070:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14071:     gsl_vector_set(x, 0, p[1]);
                   14072:     gsl_vector_set(x, 1, p[2]);
                   14073: 
                   14074:     minex_func.f = &gompertz_f;
                   14075:     minex_func.n = NDIM;
                   14076:     minex_func.params = (void *)&p; /* ??? */
                   14077:     
                   14078:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14079:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14080:     
                   14081:     printf("Iterations beginning .....\n\n");
                   14082:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14083: 
                   14084:     iteri=0;
                   14085:     while (rval == GSL_CONTINUE){
                   14086:       iteri++;
                   14087:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14088:       
                   14089:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14090:       fflush(0);
                   14091:       
                   14092:       if (status) 
                   14093:         break;
                   14094:       
                   14095:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14096:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14097:       
                   14098:       if (rval == GSL_SUCCESS)
                   14099:         printf ("converged to a local maximum at\n");
                   14100:       
                   14101:       printf("%5d ", iteri);
                   14102:       for (it = 0; it < NDIM; it++){
                   14103:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14104:       }
                   14105:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14106:     }
                   14107:     
                   14108:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14109:     
                   14110:     gsl_vector_free(x); /* initial values */
                   14111:     gsl_vector_free(ss); /* inital step size */
                   14112:     for (it=0; it<NDIM; it++){
                   14113:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14114:       fprintf(ficrespow," %.12lf", p[it]);
                   14115:     }
                   14116:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14117: #endif
                   14118: #ifdef POWELL
                   14119:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14120: #endif  
1.126     brouard  14121:     fclose(ficrespow);
                   14122:     
1.203     brouard  14123:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14124: 
                   14125:     for(i=1; i <=NDIM; i++)
                   14126:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14127:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14128:     
                   14129:     printf("\nCovariance matrix\n ");
1.203     brouard  14130:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14131:     for(i=1; i <=NDIM; i++) {
                   14132:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14133:                                printf("%f ",matcov[i][j]);
                   14134:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14135:       }
1.203     brouard  14136:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14137:     }
                   14138:     
                   14139:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14140:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14141:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14142:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14143:     }
1.302     brouard  14144:     lsurv=vector(agegomp,AGESUP);
                   14145:     lpop=vector(agegomp,AGESUP);
                   14146:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14147:     lsurv[agegomp]=100000;
                   14148:     
                   14149:     for (k=agegomp;k<=AGESUP;k++) {
                   14150:       agemortsup=k;
                   14151:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14152:     }
                   14153:     
                   14154:     for (k=agegomp;k<agemortsup;k++)
                   14155:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14156:     
                   14157:     for (k=agegomp;k<agemortsup;k++){
                   14158:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14159:       sumlpop=sumlpop+lpop[k];
                   14160:     }
                   14161:     
                   14162:     tpop[agegomp]=sumlpop;
                   14163:     for (k=agegomp;k<(agemortsup-3);k++){
                   14164:       /*  tpop[k+1]=2;*/
                   14165:       tpop[k+1]=tpop[k]-lpop[k];
                   14166:     }
                   14167:     
                   14168:     
                   14169:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14170:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14171:       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]);
                   14172:     
                   14173:     
                   14174:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14175:                ageminpar=50;
                   14176:                agemaxpar=100;
1.194     brouard  14177:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14178:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14179: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14180: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14181:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14182: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14183: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14184:     }else{
                   14185:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14186:                        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  14187:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14188:                }
1.201     brouard  14189:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14190:                     stepm, weightopt,\
                   14191:                     model,imx,p,matcov,agemortsup);
                   14192:     
1.302     brouard  14193:     free_vector(lsurv,agegomp,AGESUP);
                   14194:     free_vector(lpop,agegomp,AGESUP);
                   14195:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14196:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14197:     free_ivector(dcwave,firstobs,lastobs);
                   14198:     free_vector(agecens,firstobs,lastobs);
                   14199:     free_vector(ageexmed,firstobs,lastobs);
                   14200:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14201: #ifdef GSL
1.136     brouard  14202: #endif
1.186     brouard  14203:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14204:   /* Standard  */
                   14205:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14206:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14207:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14208:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14209:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14210:     for (k=1; k<=npar;k++)
                   14211:       printf(" %d %8.5f",k,p[k]);
                   14212:     printf("\n");
1.205     brouard  14213:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14214:       /* mlikeli uses func not funcone */
1.247     brouard  14215:       /* for(i=1;i<nlstate;i++){ */
                   14216:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14217:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14218:       /* } */
1.205     brouard  14219:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14220:     }
                   14221:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14222:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14223:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14224:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14225:     }
                   14226:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14227:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14228:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14229:           /* exit(0); */
1.126     brouard  14230:     for (k=1; k<=npar;k++)
                   14231:       printf(" %d %8.5f",k,p[k]);
                   14232:     printf("\n");
                   14233:     
                   14234:     /*--------- results files --------------*/
1.283     brouard  14235:     /* 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  14236:     
                   14237:     
                   14238:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14239:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14240:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14241: 
                   14242:     printf("#model=  1      +     age ");
                   14243:     fprintf(ficres,"#model=  1      +     age ");
                   14244:     fprintf(ficlog,"#model=  1      +     age ");
                   14245:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14246: </ul>", model);
                   14247: 
                   14248:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14249:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14250:     if(nagesqr==1){
                   14251:       printf("  + age*age  ");
                   14252:       fprintf(ficres,"  + age*age  ");
                   14253:       fprintf(ficlog,"  + age*age  ");
                   14254:       fprintf(fichtm, "<th>+ age*age</th>");
                   14255:     }
                   14256:     for(j=1;j <=ncovmodel-2;j++){
                   14257:       if(Typevar[j]==0) {
                   14258:        printf("  +      V%d  ",Tvar[j]);
                   14259:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14260:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14261:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14262:       }else if(Typevar[j]==1) {
                   14263:        printf("  +    V%d*age ",Tvar[j]);
                   14264:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14265:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14266:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14267:       }else if(Typevar[j]==2) {
                   14268:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14269:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14270:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14271:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14272:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14273:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14274:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14275:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14276:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14277:       }
                   14278:     }
                   14279:     printf("\n");
                   14280:     fprintf(ficres,"\n");
                   14281:     fprintf(ficlog,"\n");
                   14282:     fprintf(fichtm, "</tr>");
                   14283:     fprintf(fichtm, "\n");
                   14284:     
                   14285:     
1.126     brouard  14286:     for(i=1,jk=1; i <=nlstate; i++){
                   14287:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14288:        if (k != i) {
1.319     brouard  14289:          fprintf(fichtm, "<tr>");
1.225     brouard  14290:          printf("%d%d ",i,k);
                   14291:          fprintf(ficlog,"%d%d ",i,k);
                   14292:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14293:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14294:          for(j=1; j <=ncovmodel; j++){
                   14295:            printf("%12.7f ",p[jk]);
                   14296:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14297:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14298:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14299:            jk++; 
                   14300:          }
                   14301:          printf("\n");
                   14302:          fprintf(ficlog,"\n");
                   14303:          fprintf(ficres,"\n");
1.319     brouard  14304:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14305:        }
1.126     brouard  14306:       }
                   14307:     }
1.319     brouard  14308:     /* fprintf(fichtm,"</tr>\n"); */
                   14309:     fprintf(fichtm,"</table>\n");
                   14310:     fprintf(fichtm, "\n");
                   14311: 
1.203     brouard  14312:     if(mle != 0){
                   14313:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14314:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14315:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14316:       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");
                   14317:       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  14318:       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  14319:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14320:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14321:       if(nagesqr==1){
                   14322:        printf("  + age*age  ");
                   14323:        fprintf(ficres,"  + age*age  ");
                   14324:        fprintf(ficlog,"  + age*age  ");
                   14325:        fprintf(fichtm, "<th>+ age*age</th>");
                   14326:       }
                   14327:       for(j=1;j <=ncovmodel-2;j++){
                   14328:        if(Typevar[j]==0) {
                   14329:          printf("  +      V%d  ",Tvar[j]);
                   14330:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14331:        }else if(Typevar[j]==1) {
                   14332:          printf("  +    V%d*age ",Tvar[j]);
                   14333:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14334:        }else if(Typevar[j]==2) {
                   14335:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14336:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14337:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14338:        }
                   14339:       }
                   14340:       fprintf(fichtm, "</tr>\n");
                   14341:  
1.203     brouard  14342:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14343:        for(k=1; k <=(nlstate+ndeath); k++){
                   14344:          if (k != i) {
1.319     brouard  14345:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14346:            printf("%d%d ",i,k);
                   14347:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14348:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14349:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14350:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14351:              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]));
                   14352:              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  14353:              if(fabs(wald) > 1.96){
1.321     brouard  14354:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14355:              }else{
                   14356:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14357:              }
1.324     brouard  14358:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14359:              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  14360:              jk++; 
                   14361:            }
                   14362:            printf("\n");
                   14363:            fprintf(ficlog,"\n");
1.319     brouard  14364:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14365:          }
                   14366:        }
1.193     brouard  14367:       }
1.203     brouard  14368:     } /* end of hesscov and Wald tests */
1.319     brouard  14369:     fprintf(fichtm,"</table>\n");
1.225     brouard  14370:     
1.203     brouard  14371:     /*  */
1.126     brouard  14372:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14373:     printf("# Scales (for hessian or gradient estimation)\n");
                   14374:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14375:     for(i=1,jk=1; i <=nlstate; i++){
                   14376:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14377:        if (j!=i) {
                   14378:          fprintf(ficres,"%1d%1d",i,j);
                   14379:          printf("%1d%1d",i,j);
                   14380:          fprintf(ficlog,"%1d%1d",i,j);
                   14381:          for(k=1; k<=ncovmodel;k++){
                   14382:            printf(" %.5e",delti[jk]);
                   14383:            fprintf(ficlog," %.5e",delti[jk]);
                   14384:            fprintf(ficres," %.5e",delti[jk]);
                   14385:            jk++;
                   14386:          }
                   14387:          printf("\n");
                   14388:          fprintf(ficlog,"\n");
                   14389:          fprintf(ficres,"\n");
                   14390:        }
1.126     brouard  14391:       }
                   14392:     }
                   14393:     
                   14394:     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  14395:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14396:       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");
                   14397:     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");
                   14398:     /* # 121 Var(a12)\n\ */
                   14399:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14400:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14401:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14402:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14403:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14404:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14405:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14406:     
                   14407:     
                   14408:     /* Just to have a covariance matrix which will be more understandable
                   14409:        even is we still don't want to manage dictionary of variables
                   14410:     */
                   14411:     for(itimes=1;itimes<=2;itimes++){
                   14412:       jj=0;
                   14413:       for(i=1; i <=nlstate; i++){
1.225     brouard  14414:        for(j=1; j <=nlstate+ndeath; j++){
                   14415:          if(j==i) continue;
                   14416:          for(k=1; k<=ncovmodel;k++){
                   14417:            jj++;
                   14418:            ca[0]= k+'a'-1;ca[1]='\0';
                   14419:            if(itimes==1){
                   14420:              if(mle>=1)
                   14421:                printf("#%1d%1d%d",i,j,k);
                   14422:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14423:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14424:            }else{
                   14425:              if(mle>=1)
                   14426:                printf("%1d%1d%d",i,j,k);
                   14427:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14428:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14429:            }
                   14430:            ll=0;
                   14431:            for(li=1;li <=nlstate; li++){
                   14432:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14433:                if(lj==li) continue;
                   14434:                for(lk=1;lk<=ncovmodel;lk++){
                   14435:                  ll++;
                   14436:                  if(ll<=jj){
                   14437:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14438:                    if(ll<jj){
                   14439:                      if(itimes==1){
                   14440:                        if(mle>=1)
                   14441:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14442:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14443:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14444:                      }else{
                   14445:                        if(mle>=1)
                   14446:                          printf(" %.5e",matcov[jj][ll]); 
                   14447:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14448:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14449:                      }
                   14450:                    }else{
                   14451:                      if(itimes==1){
                   14452:                        if(mle>=1)
                   14453:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14454:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14455:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14456:                      }else{
                   14457:                        if(mle>=1)
                   14458:                          printf(" %.7e",matcov[jj][ll]); 
                   14459:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14460:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14461:                      }
                   14462:                    }
                   14463:                  }
                   14464:                } /* end lk */
                   14465:              } /* end lj */
                   14466:            } /* end li */
                   14467:            if(mle>=1)
                   14468:              printf("\n");
                   14469:            fprintf(ficlog,"\n");
                   14470:            fprintf(ficres,"\n");
                   14471:            numlinepar++;
                   14472:          } /* end k*/
                   14473:        } /*end j */
1.126     brouard  14474:       } /* end i */
                   14475:     } /* end itimes */
                   14476:     
                   14477:     fflush(ficlog);
                   14478:     fflush(ficres);
1.225     brouard  14479:     while(fgets(line, MAXLINE, ficpar)) {
                   14480:       /* If line starts with a # it is a comment */
                   14481:       if (line[0] == '#') {
                   14482:        numlinepar++;
                   14483:        fputs(line,stdout);
                   14484:        fputs(line,ficparo);
                   14485:        fputs(line,ficlog);
1.299     brouard  14486:        fputs(line,ficres);
1.225     brouard  14487:        continue;
                   14488:       }else
                   14489:        break;
                   14490:     }
                   14491:     
1.209     brouard  14492:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14493:     /*   ungetc(c,ficpar); */
                   14494:     /*   fgets(line, MAXLINE, ficpar); */
                   14495:     /*   fputs(line,stdout); */
                   14496:     /*   fputs(line,ficparo); */
                   14497:     /* } */
                   14498:     /* ungetc(c,ficpar); */
1.126     brouard  14499:     
                   14500:     estepm=0;
1.209     brouard  14501:     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  14502:       
                   14503:       if (num_filled != 6) {
                   14504:        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);
                   14505:        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);
                   14506:        goto end;
                   14507:       }
                   14508:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14509:     }
                   14510:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14511:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14512:     
1.209     brouard  14513:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14514:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14515:     if (fage <= 2) {
                   14516:       bage = ageminpar;
                   14517:       fage = agemaxpar;
                   14518:     }
                   14519:     
                   14520:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14521:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14522:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14523:                
1.186     brouard  14524:     /* Other stuffs, more or less useful */    
1.254     brouard  14525:     while(fgets(line, MAXLINE, ficpar)) {
                   14526:       /* If line starts with a # it is a comment */
                   14527:       if (line[0] == '#') {
                   14528:        numlinepar++;
                   14529:        fputs(line,stdout);
                   14530:        fputs(line,ficparo);
                   14531:        fputs(line,ficlog);
1.299     brouard  14532:        fputs(line,ficres);
1.254     brouard  14533:        continue;
                   14534:       }else
                   14535:        break;
                   14536:     }
                   14537: 
                   14538:     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){
                   14539:       
                   14540:       if (num_filled != 7) {
                   14541:        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);
                   14542:        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);
                   14543:        goto end;
                   14544:       }
                   14545:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14546:       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);
                   14547:       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);
                   14548:       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  14549:     }
1.254     brouard  14550: 
                   14551:     while(fgets(line, MAXLINE, ficpar)) {
                   14552:       /* If line starts with a # it is a comment */
                   14553:       if (line[0] == '#') {
                   14554:        numlinepar++;
                   14555:        fputs(line,stdout);
                   14556:        fputs(line,ficparo);
                   14557:        fputs(line,ficlog);
1.299     brouard  14558:        fputs(line,ficres);
1.254     brouard  14559:        continue;
                   14560:       }else
                   14561:        break;
1.126     brouard  14562:     }
                   14563:     
                   14564:     
                   14565:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14566:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14567:     
1.254     brouard  14568:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14569:       if (num_filled != 1) {
                   14570:        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);
                   14571:        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);
                   14572:        goto end;
                   14573:       }
                   14574:       printf("pop_based=%d\n",popbased);
                   14575:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14576:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14577:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14578:     }
                   14579:      
1.258     brouard  14580:     /* Results */
1.332     brouard  14581:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14582:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14583:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14584:     endishere=0;
1.258     brouard  14585:     nresult=0;
1.308     brouard  14586:     parameterline=0;
1.258     brouard  14587:     do{
                   14588:       if(!fgets(line, MAXLINE, ficpar)){
                   14589:        endishere=1;
1.308     brouard  14590:        parameterline=15;
1.258     brouard  14591:       }else if (line[0] == '#') {
                   14592:        /* If line starts with a # it is a comment */
1.254     brouard  14593:        numlinepar++;
                   14594:        fputs(line,stdout);
                   14595:        fputs(line,ficparo);
                   14596:        fputs(line,ficlog);
1.299     brouard  14597:        fputs(line,ficres);
1.254     brouard  14598:        continue;
1.258     brouard  14599:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14600:        parameterline=11;
1.296     brouard  14601:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14602:        parameterline=12;
1.307     brouard  14603:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14604:        parameterline=13;
1.307     brouard  14605:       }
1.258     brouard  14606:       else{
                   14607:        parameterline=14;
1.254     brouard  14608:       }
1.308     brouard  14609:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14610:       case 11:
1.296     brouard  14611:        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)){
                   14612:                  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  14613:          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);
                   14614:          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);
                   14615:          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);
                   14616:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14617:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14618:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14619:           prvforecast = 1;
                   14620:        } 
                   14621:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14622:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14623:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14624:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14625:           prvforecast = 2;
                   14626:        }
                   14627:        else {
                   14628:          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);
                   14629:          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);
                   14630:          goto end;
1.258     brouard  14631:        }
1.254     brouard  14632:        break;
1.258     brouard  14633:       case 12:
1.296     brouard  14634:        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)){
                   14635:           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);
                   14636:          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);
                   14637:          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);
                   14638:          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);
                   14639:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14640:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14641:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14642:           prvbackcast = 1;
                   14643:        } 
                   14644:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14645:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14646:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14647:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14648:           prvbackcast = 2;
                   14649:        }
                   14650:        else {
                   14651:          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);
                   14652:          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);
                   14653:          goto end;
1.258     brouard  14654:        }
1.230     brouard  14655:        break;
1.258     brouard  14656:       case 13:
1.332     brouard  14657:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14658:        nresult++; /* Sum of resultlines */
1.342     brouard  14659:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14660:        /* removefirstspace(&resultlineori); */
                   14661:        
                   14662:        if(strstr(resultlineori,"v") !=0){
                   14663:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14664:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14665:          return 1;
                   14666:        }
                   14667:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14668:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14669:        if(nresult > MAXRESULTLINESPONE-1){
                   14670:          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);
                   14671:          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  14672:          goto end;
                   14673:        }
1.332     brouard  14674:        
1.310     brouard  14675:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14676:          fprintf(ficparo,"result: %s\n",resultline);
                   14677:          fprintf(ficres,"result: %s\n",resultline);
                   14678:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14679:        } else
                   14680:          goto end;
1.307     brouard  14681:        break;
                   14682:       case 14:
                   14683:        printf("Error: Unknown command '%s'\n",line);
                   14684:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14685:        if(line[0] == ' ' || line[0] == '\n'){
                   14686:          printf("It should not be an empty line '%s'\n",line);
                   14687:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14688:        }         
1.307     brouard  14689:        if(ncovmodel >=2 && nresult==0 ){
                   14690:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14691:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14692:        }
1.307     brouard  14693:        /* goto end; */
                   14694:        break;
1.308     brouard  14695:       case 15:
                   14696:        printf("End of resultlines.\n");
                   14697:        fprintf(ficlog,"End of resultlines.\n");
                   14698:        break;
                   14699:       default: /* parameterline =0 */
1.307     brouard  14700:        nresult=1;
                   14701:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14702:       } /* End switch parameterline */
                   14703:     }while(endishere==0); /* End do */
1.126     brouard  14704:     
1.230     brouard  14705:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14706:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14707:     
                   14708:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14709:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14710:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14711: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14712: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14713:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14714: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14715: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14716:     }else{
1.270     brouard  14717:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14718:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14719:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14720:       if(prvforecast==1){
                   14721:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14722:         jprojd=jproj1;
                   14723:         mprojd=mproj1;
                   14724:         anprojd=anproj1;
                   14725:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14726:         jprojf=jproj2;
                   14727:         mprojf=mproj2;
                   14728:         anprojf=anproj2;
                   14729:       } else if(prvforecast == 2){
                   14730:         dateprojd=dateintmean;
                   14731:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14732:         dateprojf=dateintmean+yrfproj;
                   14733:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14734:       }
                   14735:       if(prvbackcast==1){
                   14736:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14737:         jbackd=jback1;
                   14738:         mbackd=mback1;
                   14739:         anbackd=anback1;
                   14740:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14741:         jbackf=jback2;
                   14742:         mbackf=mback2;
                   14743:         anbackf=anback2;
                   14744:       } else if(prvbackcast == 2){
                   14745:         datebackd=dateintmean;
                   14746:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14747:         datebackf=dateintmean-yrbproj;
                   14748:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14749:       }
                   14750:       
1.350   ! brouard  14751:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14752:     }
                   14753:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14754:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14755:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14756:                
1.225     brouard  14757:     /*------------ free_vector  -------------*/
                   14758:     /*  chdir(path); */
1.220     brouard  14759:                
1.215     brouard  14760:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14761:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14762:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14763:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14764:     free_lvector(num,firstobs,lastobs);
                   14765:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14766:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14767:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14768:     fclose(ficparo);
                   14769:     fclose(ficres);
1.220     brouard  14770:                
                   14771:                
1.186     brouard  14772:     /* Other results (useful)*/
1.220     brouard  14773:                
                   14774:                
1.126     brouard  14775:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14776:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14777:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14778:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14779:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14780:     fclose(ficrespl);
                   14781: 
                   14782:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14783:     /*#include "hpijx.h"*/
1.332     brouard  14784:     /** 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?*/
                   14785:     /* calls hpxij with combination k */
1.180     brouard  14786:     hPijx(p, bage, fage);
1.145     brouard  14787:     fclose(ficrespij);
1.227     brouard  14788:     
1.220     brouard  14789:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14790:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14791:     k=1;
1.126     brouard  14792:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14793:     
1.269     brouard  14794:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14795:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14796:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14797:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14798:        for(k=1;k<=ncovcombmax;k++)
                   14799:          probs[i][j][k]=0.;
1.269     brouard  14800:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14801:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14802:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14803:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14804:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14805:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14806:          for(k=1;k<=ncovcombmax;k++)
                   14807:            mobaverages[i][j][k]=0.;
1.219     brouard  14808:       mobaverage=mobaverages;
                   14809:       if (mobilav!=0) {
1.235     brouard  14810:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14811:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14812:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14813:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14814:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14815:        }
1.269     brouard  14816:       } else if (mobilavproj !=0) {
1.235     brouard  14817:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14818:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14819:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14820:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14821:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14822:        }
1.269     brouard  14823:       }else{
                   14824:        printf("Internal error moving average\n");
                   14825:        fflush(stdout);
                   14826:        exit(1);
1.219     brouard  14827:       }
                   14828:     }/* end if moving average */
1.227     brouard  14829:     
1.126     brouard  14830:     /*---------- Forecasting ------------------*/
1.296     brouard  14831:     if(prevfcast==1){ 
                   14832:       /*   /\*    if(stepm ==1){*\/ */
                   14833:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14834:       /*This done previously after freqsummary.*/
                   14835:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14836:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14837:       
                   14838:       /* } else if (prvforecast==2){ */
                   14839:       /*   /\*    if(stepm ==1){*\/ */
                   14840:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14841:       /* } */
                   14842:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14843:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14844:     }
1.269     brouard  14845: 
1.296     brouard  14846:     /* Prevbcasting */
                   14847:     if(prevbcast==1){
1.219     brouard  14848:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14849:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14850:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14851: 
                   14852:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14853: 
                   14854:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14855: 
1.219     brouard  14856:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14857:       fclose(ficresplb);
                   14858: 
1.222     brouard  14859:       hBijx(p, bage, fage, mobaverage);
                   14860:       fclose(ficrespijb);
1.219     brouard  14861: 
1.296     brouard  14862:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14863:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14864:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14865:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14866:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14867:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14868: 
                   14869:       
1.269     brouard  14870:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14871: 
                   14872:       
1.269     brouard  14873:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14874:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14875:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14876:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14877:     }    /* end  Prevbcasting */
1.268     brouard  14878:  
1.186     brouard  14879:  
                   14880:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14881: 
1.215     brouard  14882:     free_ivector(wav,1,imx);
                   14883:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14884:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14885:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14886:                
                   14887:                
1.127     brouard  14888:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14889:                
1.201     brouard  14890:     strcpy(filerese,"E_");
                   14891:     strcat(filerese,fileresu);
1.126     brouard  14892:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14893:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14894:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14895:     }
1.208     brouard  14896:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14897:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14898: 
                   14899:     pstamp(ficreseij);
1.219     brouard  14900:                
1.235     brouard  14901:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14902:     if (cptcovn < 1){i1=1;}
                   14903:     
                   14904:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14905:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14906:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14907:        continue;
1.219     brouard  14908:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14909:       printf("\n#****** ");
1.225     brouard  14910:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14911:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14912:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14913:       }
                   14914:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14915:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14916:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14917:       }
                   14918:       fprintf(ficreseij,"******\n");
1.235     brouard  14919:       printf("******\n");
1.219     brouard  14920:       
                   14921:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14922:       oldm=oldms;savm=savms;
1.330     brouard  14923:       /* 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  14924:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14925:       
1.219     brouard  14926:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14927:     }
                   14928:     fclose(ficreseij);
1.208     brouard  14929:     printf("done evsij\n");fflush(stdout);
                   14930:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14931: 
1.218     brouard  14932:                
1.227     brouard  14933:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14934:     /* Should be moved in a function */                
1.201     brouard  14935:     strcpy(filerest,"T_");
                   14936:     strcat(filerest,fileresu);
1.127     brouard  14937:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14938:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14939:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14940:     }
1.208     brouard  14941:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14942:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14943:     strcpy(fileresstde,"STDE_");
                   14944:     strcat(fileresstde,fileresu);
1.126     brouard  14945:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14946:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14947:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14948:     }
1.227     brouard  14949:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14950:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14951: 
1.201     brouard  14952:     strcpy(filerescve,"CVE_");
                   14953:     strcat(filerescve,fileresu);
1.126     brouard  14954:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14955:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14956:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14957:     }
1.227     brouard  14958:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14959:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14960: 
1.201     brouard  14961:     strcpy(fileresv,"V_");
                   14962:     strcat(fileresv,fileresu);
1.126     brouard  14963:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14964:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14965:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14966:     }
1.227     brouard  14967:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14968:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14969: 
1.235     brouard  14970:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14971:     if (cptcovn < 1){i1=1;}
                   14972:     
1.334     brouard  14973:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14974:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14975:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14976:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14977:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14978:       /* */
                   14979:       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  14980:        continue;
1.350   ! brouard  14981:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  14982:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14983:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14984:       /* It might not be a good idea to mix dummies and quantitative */
                   14985:       /* 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 *\/ */
                   14986:       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 */
                   14987:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14988:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14989:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14990:         * (V5 is quanti) V4 and V3 are dummies
                   14991:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14992:         *                                                              l=1 l=2
                   14993:         *                                                           k=1  1   1   0   0
                   14994:         *                                                           k=2  2   1   1   0
                   14995:         *                                                           k=3 [1] [2]  0   1
                   14996:         *                                                           k=4  2   2   1   1
                   14997:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14998:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14999:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15000:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15001:         */
                   15002:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15003:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15004: /* We give up with the combinations!! */
1.342     brouard  15005:        /* if(debugILK) */
                   15006:        /*   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  15007: 
                   15008:        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  15009:          /* 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] */
                   15010:          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  */
                   15011:          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  */
                   15012:          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  15013:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15014:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15015:          }else{
                   15016:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15017:          }
                   15018:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15019:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15020:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15021:          /* For each selected (single) quantitative value */
1.337     brouard  15022:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15023:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15024:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15025:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15026:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15027:          }else{
                   15028:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15029:          }
                   15030:        }else{
                   15031:          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 */
                   15032:          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 */
                   15033:          exit(1);
                   15034:        }
1.335     brouard  15035:       } /* End loop for each variable in the resultline */
1.334     brouard  15036:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15037:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15038:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15039:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15040:       /* }      */
1.208     brouard  15041:       fprintf(ficrest,"******\n");
1.227     brouard  15042:       fprintf(ficlog,"******\n");
                   15043:       printf("******\n");
1.208     brouard  15044:       
                   15045:       fprintf(ficresstdeij,"\n#****** ");
                   15046:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15047:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15048:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15049:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15050:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15051:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15052:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15053:       }
                   15054:       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  15055:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15056:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15057:       }        
1.208     brouard  15058:       fprintf(ficresstdeij,"******\n");
                   15059:       fprintf(ficrescveij,"******\n");
                   15060:       
                   15061:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15062:       /* pstamp(ficresvij); */
1.225     brouard  15063:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15064:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15065:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15066:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15067:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15068:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15069:       }        
1.208     brouard  15070:       fprintf(ficresvij,"******\n");
                   15071:       
                   15072:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15073:       oldm=oldms;savm=savms;
1.235     brouard  15074:       printf(" cvevsij ");
                   15075:       fprintf(ficlog, " cvevsij ");
                   15076:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15077:       printf(" end cvevsij \n ");
                   15078:       fprintf(ficlog, " end cvevsij \n ");
                   15079:       
                   15080:       /*
                   15081:        */
                   15082:       /* goto endfree; */
                   15083:       
                   15084:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15085:       pstamp(ficrest);
                   15086:       
1.269     brouard  15087:       epj=vector(1,nlstate+1);
1.208     brouard  15088:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15089:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15090:        cptcod= 0; /* To be deleted */
                   15091:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15092:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15093:        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  15094:        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 ");
                   15095:        if(vpopbased==1)
                   15096:          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);
                   15097:        else
1.288     brouard  15098:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15099:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15100:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15101:        fprintf(ficrest,"\n");
                   15102:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15103:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15104:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15105:        for(age=bage; age <=fage ;age++){
1.235     brouard  15106:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15107:          if (vpopbased==1) {
                   15108:            if(mobilav ==0){
                   15109:              for(i=1; i<=nlstate;i++)
                   15110:                prlim[i][i]=probs[(int)age][i][k];
                   15111:            }else{ /* mobilav */ 
                   15112:              for(i=1; i<=nlstate;i++)
                   15113:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15114:            }
                   15115:          }
1.219     brouard  15116:          
1.227     brouard  15117:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15118:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15119:          /* printf(" age %4.0f ",age); */
                   15120:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15121:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15122:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15123:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15124:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15125:            }
                   15126:            epj[nlstate+1] +=epj[j];
                   15127:          }
                   15128:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15129:          
1.227     brouard  15130:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15131:            for(j=1;j <=nlstate;j++)
                   15132:              vepp += vareij[i][j][(int)age];
                   15133:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15134:          for(j=1;j <=nlstate;j++){
                   15135:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15136:          }
                   15137:          fprintf(ficrest,"\n");
                   15138:        }
1.208     brouard  15139:       } /* End vpopbased */
1.269     brouard  15140:       free_vector(epj,1,nlstate+1);
1.208     brouard  15141:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15142:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15143:       printf("done selection\n");fflush(stdout);
                   15144:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15145:       
1.335     brouard  15146:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15147: 
                   15148:     printf("done State-specific expectancies\n");fflush(stdout);
                   15149:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15150: 
1.335     brouard  15151:     /* variance-covariance of forward period prevalence */
1.269     brouard  15152:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15153: 
1.227     brouard  15154:     
1.290     brouard  15155:     free_vector(weight,firstobs,lastobs);
1.349     brouard  15156:     free_imatrix(Tvardk,-1,NCOVMAX,1,2);
1.227     brouard  15157:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15158:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15159:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15160:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15161:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15162:     free_ivector(tab,1,NCOVMAX);
                   15163:     fclose(ficresstdeij);
                   15164:     fclose(ficrescveij);
                   15165:     fclose(ficresvij);
                   15166:     fclose(ficrest);
                   15167:     fclose(ficpar);
                   15168:     
                   15169:     
1.126     brouard  15170:     /*---------- End : free ----------------*/
1.219     brouard  15171:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15172:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15173:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15174:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15175:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15176:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15177:   /* endfree:*/
                   15178:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15179:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15180:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15181:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15182:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15183:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15184:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15185:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15186:   free_matrix(matcov,1,npar,1,npar);
                   15187:   free_matrix(hess,1,npar,1,npar);
                   15188:   /*free_vector(delti,1,npar);*/
                   15189:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15190:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15191:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15192:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15193:   
                   15194:   free_ivector(ncodemax,1,NCOVMAX);
                   15195:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15196:   free_ivector(Dummy,-1,NCOVMAX);
                   15197:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15198:   free_ivector(DummyV,-1,NCOVMAX);
                   15199:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15200:   free_ivector(Typevar,-1,NCOVMAX);
                   15201:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15202:   free_ivector(TvarsQ,1,NCOVMAX);
                   15203:   free_ivector(TvarsQind,1,NCOVMAX);
                   15204:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15205:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15206:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15207:   free_ivector(TvarFD,1,NCOVMAX);
                   15208:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15209:   free_ivector(TvarF,1,NCOVMAX);
                   15210:   free_ivector(TvarFind,1,NCOVMAX);
                   15211:   free_ivector(TvarV,1,NCOVMAX);
                   15212:   free_ivector(TvarVind,1,NCOVMAX);
                   15213:   free_ivector(TvarA,1,NCOVMAX);
                   15214:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15215:   free_ivector(TvarFQ,1,NCOVMAX);
                   15216:   free_ivector(TvarFQind,1,NCOVMAX);
                   15217:   free_ivector(TvarVD,1,NCOVMAX);
                   15218:   free_ivector(TvarVDind,1,NCOVMAX);
                   15219:   free_ivector(TvarVQ,1,NCOVMAX);
                   15220:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15221:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15222:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15223:   free_ivector(TvarVVA,1,NCOVMAX);
                   15224:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15225:   free_ivector(TvarVV,1,NCOVMAX);
                   15226:   free_ivector(TvarVVind,1,NCOVMAX);
                   15227:   
1.230     brouard  15228:   free_ivector(Tvarsel,1,NCOVMAX);
                   15229:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15230:   free_ivector(Tposprod,1,NCOVMAX);
                   15231:   free_ivector(Tprod,1,NCOVMAX);
                   15232:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15233:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15234:   free_ivector(Tage,1,NCOVMAX);
                   15235:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15236:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15237:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15238: 
                   15239:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15240: 
1.227     brouard  15241:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15242:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15243:   fflush(fichtm);
                   15244:   fflush(ficgp);
                   15245:   
1.227     brouard  15246:   
1.126     brouard  15247:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15248:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15249:     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  15250:   }else{
                   15251:     printf("End of Imach\n");
                   15252:     fprintf(ficlog,"End of Imach\n");
                   15253:   }
                   15254:   printf("See log file on %s\n",filelog);
                   15255:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15256:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15257:   rend_time = time(NULL);  
                   15258:   end_time = *localtime(&rend_time);
                   15259:   /* tml = *localtime(&end_time.tm_sec); */
                   15260:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15261:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15262:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15263:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15264:   
1.157     brouard  15265:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15266:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15267:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15268:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15269: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15270:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15271:   fclose(fichtm);
                   15272:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15273:   fclose(fichtmcov);
                   15274:   fclose(ficgp);
                   15275:   fclose(ficlog);
                   15276:   /*------ End -----------*/
1.227     brouard  15277:   
1.281     brouard  15278: 
                   15279: /* Executes gnuplot */
1.227     brouard  15280:   
                   15281:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15282: #ifdef WIN32
1.227     brouard  15283:   if (_chdir(pathcd) != 0)
                   15284:     printf("Can't move to directory %s!\n",path);
                   15285:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15286: #else
1.227     brouard  15287:     if(chdir(pathcd) != 0)
                   15288:       printf("Can't move to directory %s!\n", path);
                   15289:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15290: #endif 
1.126     brouard  15291:     printf("Current directory %s!\n",pathcd);
                   15292:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15293:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15294: #ifdef _WIN32
1.126     brouard  15295:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15296: #endif
                   15297:   if(!stat(plotcmd,&info)){
1.158     brouard  15298:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15299:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15300:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15301:     }else
                   15302:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15303: #ifdef __unix
1.126     brouard  15304:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15305:     if(!stat(plotcmd,&info)){
1.158     brouard  15306:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15307:     }else
                   15308:       strcpy(pplotcmd,plotcmd);
                   15309: #endif
                   15310:   }else
                   15311:     strcpy(pplotcmd,plotcmd);
                   15312:   
                   15313:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15314:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15315:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15316:   
1.126     brouard  15317:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15318:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15319:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15320:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15321:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15322:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15323:       strcpy(plotcmd,pplotcmd);
                   15324:     }
1.126     brouard  15325:   }
1.158     brouard  15326:   printf(" Successful, please wait...");
1.126     brouard  15327:   while (z[0] != 'q') {
                   15328:     /* chdir(path); */
1.154     brouard  15329:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15330:     scanf("%s",z);
                   15331: /*     if (z[0] == 'c') system("./imach"); */
                   15332:     if (z[0] == 'e') {
1.158     brouard  15333: #ifdef __APPLE__
1.152     brouard  15334:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15335: #elif __linux
                   15336:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15337: #else
1.152     brouard  15338:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15339: #endif
                   15340:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15341:       system(pplotcmd);
1.126     brouard  15342:     }
                   15343:     else if (z[0] == 'g') system(plotcmd);
                   15344:     else if (z[0] == 'q') exit(0);
                   15345:   }
1.227     brouard  15346: end:
1.126     brouard  15347:   while (z[0] != 'q') {
1.195     brouard  15348:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15349:     scanf("%s",z);
                   15350:   }
1.283     brouard  15351:   printf("End\n");
1.282     brouard  15352:   exit(0);
1.126     brouard  15353: }

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