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

1.352   ! brouard     1: /* $Id: imach.c,v 1.351 2023/04/29 10:43:47 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.352   ! brouard     4:   Revision 1.351  2023/04/29 10:43:47  brouard
        !             5:   Summary: 099r45
        !             6: 
1.351     brouard     7:   Revision 1.350  2023/04/24 11:38:06  brouard
                      8:   *** empty log message ***
                      9: 
1.350     brouard    10:   Revision 1.349  2023/01/31 09:19:37  brouard
                     11:   Summary: Improvements in models with age*Vn*Vm
                     12: 
1.348     brouard    13:   Revision 1.347  2022/09/18 14:36:44  brouard
                     14:   Summary: version 0.99r42
                     15: 
1.347     brouard    16:   Revision 1.346  2022/09/16 13:52:36  brouard
                     17:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     18: 
1.346     brouard    19:   Revision 1.345  2022/09/16 13:40:11  brouard
                     20:   Summary: Version 0.99r41
                     21: 
                     22:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     23: 
1.345     brouard    24:   Revision 1.344  2022/09/14 19:33:30  brouard
                     25:   Summary: version 0.99r40
                     26: 
                     27:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     28: 
1.344     brouard    29:   Revision 1.343  2022/09/14 14:22:16  brouard
                     30:   Summary: version 0.99r39
                     31: 
                     32:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     33:   (fixed or time varying), using new last columns of
                     34:   ILK_parameter.txt file.
                     35: 
1.343     brouard    36:   Revision 1.342  2022/09/11 19:54:09  brouard
                     37:   Summary: 0.99r38
                     38: 
                     39:   * imach.c (Module): Adding timevarying products of any kinds,
                     40:   should work before shifting cotvar from ncovcol+nqv columns in
                     41:   order to have a correspondance between the column of cotvar and
                     42:   the id of column.
                     43:   (Module): Some cleaning and adding covariates in ILK.txt
                     44: 
1.342     brouard    45:   Revision 1.341  2022/09/11 07:58:42  brouard
                     46:   Summary: Version 0.99r38
                     47: 
                     48:   After adding change in cotvar.
                     49: 
1.341     brouard    50:   Revision 1.340  2022/09/11 07:53:11  brouard
                     51:   Summary: Version imach 0.99r37
                     52: 
                     53:   * imach.c (Module): Adding timevarying products of any kinds,
                     54:   should work before shifting cotvar from ncovcol+nqv columns in
                     55:   order to have a correspondance between the column of cotvar and
                     56:   the id of column.
                     57: 
1.340     brouard    58:   Revision 1.339  2022/09/09 17:55:22  brouard
                     59:   Summary: version 0.99r37
                     60: 
                     61:   * imach.c (Module): Many improvements for fixing products of fixed
                     62:   timevarying as well as fixed * fixed, and test with quantitative
                     63:   covariate.
                     64: 
1.339     brouard    65:   Revision 1.338  2022/09/04 17:40:33  brouard
                     66:   Summary: 0.99r36
                     67: 
                     68:   * imach.c (Module): Now the easy runs i.e. without result or
                     69:   model=1+age only did not work. The defautl combination should be 1
                     70:   and not 0 because everything hasn't been tranformed yet.
                     71: 
1.338     brouard    72:   Revision 1.337  2022/09/02 14:26:02  brouard
                     73:   Summary: version 0.99r35
                     74: 
                     75:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     76:   1+age+V1+V1*age for females and 1+age for females only
                     77:   (education=1 noweight)
                     78: 
1.337     brouard    79:   Revision 1.336  2022/08/31 09:52:36  brouard
                     80:   *** empty log message ***
                     81: 
1.336     brouard    82:   Revision 1.335  2022/08/31 08:23:16  brouard
                     83:   Summary: improvements...
                     84: 
1.335     brouard    85:   Revision 1.334  2022/08/25 09:08:41  brouard
                     86:   Summary: In progress for quantitative
                     87: 
1.334     brouard    88:   Revision 1.333  2022/08/21 09:10:30  brouard
                     89:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     90:   reassigning covariates: my first idea was that people will always
                     91:   use the first covariate V1 into the model but in fact they are
                     92:   producing data with many covariates and can use an equation model
                     93:   with some of the covariate; it means that in a model V2+V3 instead
                     94:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     95:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     96:   the equation model is restricted to two variables only (V2, V3)
                     97:   and the combination for V2 should be codtabm(k,1) instead of
                     98:   (codtabm(k,2), and the code should be
                     99:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    100:   made. All of these should be simplified once a day like we did in
                    101:   hpxij() for example by using precov[nres] which is computed in
                    102:   decoderesult for each nres of each resultline. Loop should be done
                    103:   on the equation model globally by distinguishing only product with
                    104:   age (which are changing with age) and no more on type of
                    105:   covariates, single dummies, single covariates.
                    106: 
1.333     brouard   107:   Revision 1.332  2022/08/21 09:06:25  brouard
                    108:   Summary: Version 0.99r33
                    109: 
                    110:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    111:   reassigning covariates: my first idea was that people will always
                    112:   use the first covariate V1 into the model but in fact they are
                    113:   producing data with many covariates and can use an equation model
                    114:   with some of the covariate; it means that in a model V2+V3 instead
                    115:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    116:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    117:   the equation model is restricted to two variables only (V2, V3)
                    118:   and the combination for V2 should be codtabm(k,1) instead of
                    119:   (codtabm(k,2), and the code should be
                    120:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    121:   made. All of these should be simplified once a day like we did in
                    122:   hpxij() for example by using precov[nres] which is computed in
                    123:   decoderesult for each nres of each resultline. Loop should be done
                    124:   on the equation model globally by distinguishing only product with
                    125:   age (which are changing with age) and no more on type of
                    126:   covariates, single dummies, single covariates.
                    127: 
1.332     brouard   128:   Revision 1.331  2022/08/07 05:40:09  brouard
                    129:   *** empty log message ***
                    130: 
1.331     brouard   131:   Revision 1.330  2022/08/06 07:18:25  brouard
                    132:   Summary: last 0.99r31
                    133: 
                    134:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    135: 
1.330     brouard   136:   Revision 1.329  2022/08/03 17:29:54  brouard
                    137:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    138: 
1.329     brouard   139:   Revision 1.328  2022/07/27 17:40:48  brouard
                    140:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    141: 
1.328     brouard   142:   Revision 1.327  2022/07/27 14:47:35  brouard
                    143:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    144: 
1.327     brouard   145:   Revision 1.326  2022/07/26 17:33:55  brouard
                    146:   Summary: some test with nres=1
                    147: 
1.326     brouard   148:   Revision 1.325  2022/07/25 14:27:23  brouard
                    149:   Summary: r30
                    150: 
                    151:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    152:   coredumped, revealed by Feiuno, thank you.
                    153: 
1.325     brouard   154:   Revision 1.324  2022/07/23 17:44:26  brouard
                    155:   *** empty log message ***
                    156: 
1.324     brouard   157:   Revision 1.323  2022/07/22 12:30:08  brouard
                    158:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    159: 
1.323     brouard   160:   Revision 1.322  2022/07/22 12:27:48  brouard
                    161:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    162: 
1.322     brouard   163:   Revision 1.321  2022/07/22 12:04:24  brouard
                    164:   Summary: r28
                    165: 
                    166:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    167: 
1.321     brouard   168:   Revision 1.320  2022/06/02 05:10:11  brouard
                    169:   *** empty log message ***
                    170: 
1.320     brouard   171:   Revision 1.319  2022/06/02 04:45:11  brouard
                    172:   * imach.c (Module): Adding the Wald tests from the log to the main
                    173:   htm for better display of the maximum likelihood estimators.
                    174: 
1.319     brouard   175:   Revision 1.318  2022/05/24 08:10:59  brouard
                    176:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    177:   of confidencce intervals with product in the equation modelC
                    178: 
1.318     brouard   179:   Revision 1.317  2022/05/15 15:06:23  brouard
                    180:   * imach.c (Module):  Some minor improvements
                    181: 
1.317     brouard   182:   Revision 1.316  2022/05/11 15:11:31  brouard
                    183:   Summary: r27
                    184: 
1.316     brouard   185:   Revision 1.315  2022/05/11 15:06:32  brouard
                    186:   *** empty log message ***
                    187: 
1.315     brouard   188:   Revision 1.314  2022/04/13 17:43:09  brouard
                    189:   * imach.c (Module): Adding link to text data files
                    190: 
1.314     brouard   191:   Revision 1.313  2022/04/11 15:57:42  brouard
                    192:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    193: 
1.313     brouard   194:   Revision 1.312  2022/04/05 21:24:39  brouard
                    195:   *** empty log message ***
                    196: 
1.312     brouard   197:   Revision 1.311  2022/04/05 21:03:51  brouard
                    198:   Summary: Fixed quantitative covariates
                    199: 
                    200:          Fixed covariates (dummy or quantitative)
                    201:        with missing values have never been allowed but are ERRORS and
                    202:        program quits. Standard deviations of fixed covariates were
                    203:        wrongly computed. Mean and standard deviations of time varying
                    204:        covariates are still not computed.
                    205: 
1.311     brouard   206:   Revision 1.310  2022/03/17 08:45:53  brouard
                    207:   Summary: 99r25
                    208: 
                    209:   Improving detection of errors: result lines should be compatible with
                    210:   the model.
                    211: 
1.310     brouard   212:   Revision 1.309  2021/05/20 12:39:14  brouard
                    213:   Summary: Version 0.99r24
                    214: 
1.309     brouard   215:   Revision 1.308  2021/03/31 13:11:57  brouard
                    216:   Summary: Version 0.99r23
                    217: 
                    218: 
                    219:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    220: 
1.308     brouard   221:   Revision 1.307  2021/03/08 18:11:32  brouard
                    222:   Summary: 0.99r22 fixed bug on result:
                    223: 
1.307     brouard   224:   Revision 1.306  2021/02/20 15:44:02  brouard
                    225:   Summary: Version 0.99r21
                    226: 
                    227:   * imach.c (Module): Fix bug on quitting after result lines!
                    228:   (Module): Version 0.99r21
                    229: 
1.306     brouard   230:   Revision 1.305  2021/02/20 15:28:30  brouard
                    231:   * imach.c (Module): Fix bug on quitting after result lines!
                    232: 
1.305     brouard   233:   Revision 1.304  2021/02/12 11:34:20  brouard
                    234:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    235: 
1.304     brouard   236:   Revision 1.303  2021/02/11 19:50:15  brouard
                    237:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    238: 
1.303     brouard   239:   Revision 1.302  2020/02/22 21:00:05  brouard
                    240:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    241:   and life table from the data without any state)
                    242: 
1.302     brouard   243:   Revision 1.301  2019/06/04 13:51:20  brouard
                    244:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    245: 
1.301     brouard   246:   Revision 1.300  2019/05/22 19:09:45  brouard
                    247:   Summary: version 0.99r19 of May 2019
                    248: 
1.300     brouard   249:   Revision 1.299  2019/05/22 18:37:08  brouard
                    250:   Summary: Cleaned 0.99r19
                    251: 
1.299     brouard   252:   Revision 1.298  2019/05/22 18:19:56  brouard
                    253:   *** empty log message ***
                    254: 
1.298     brouard   255:   Revision 1.297  2019/05/22 17:56:10  brouard
                    256:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    257: 
1.297     brouard   258:   Revision 1.296  2019/05/20 13:03:18  brouard
                    259:   Summary: Projection syntax simplified
                    260: 
                    261: 
                    262:   We can now start projections, forward or backward, from the mean date
                    263:   of inteviews up to or down to a number of years of projection:
                    264:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    265:   or
                    266:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    267:   or
                    268:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    269:   or
                    270:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    271: 
1.296     brouard   272:   Revision 1.295  2019/05/18 09:52:50  brouard
                    273:   Summary: doxygen tex bug
                    274: 
1.295     brouard   275:   Revision 1.294  2019/05/16 14:54:33  brouard
                    276:   Summary: There was some wrong lines added
                    277: 
1.294     brouard   278:   Revision 1.293  2019/05/09 15:17:34  brouard
                    279:   *** empty log message ***
                    280: 
1.293     brouard   281:   Revision 1.292  2019/05/09 14:17:20  brouard
                    282:   Summary: Some updates
                    283: 
1.292     brouard   284:   Revision 1.291  2019/05/09 13:44:18  brouard
                    285:   Summary: Before ncovmax
                    286: 
1.291     brouard   287:   Revision 1.290  2019/05/09 13:39:37  brouard
                    288:   Summary: 0.99r18 unlimited number of individuals
                    289: 
                    290:   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.
                    291: 
1.290     brouard   292:   Revision 1.289  2018/12/13 09:16:26  brouard
                    293:   Summary: Bug for young ages (<-30) will be in r17
                    294: 
1.289     brouard   295:   Revision 1.288  2018/05/02 20:58:27  brouard
                    296:   Summary: Some bugs fixed
                    297: 
1.288     brouard   298:   Revision 1.287  2018/05/01 17:57:25  brouard
                    299:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    300: 
1.287     brouard   301:   Revision 1.286  2018/04/27 14:27:04  brouard
                    302:   Summary: some minor bugs
                    303: 
1.286     brouard   304:   Revision 1.285  2018/04/21 21:02:16  brouard
                    305:   Summary: Some bugs fixed, valgrind tested
                    306: 
1.285     brouard   307:   Revision 1.284  2018/04/20 05:22:13  brouard
                    308:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    309: 
1.284     brouard   310:   Revision 1.283  2018/04/19 14:49:16  brouard
                    311:   Summary: Some minor bugs fixed
                    312: 
1.283     brouard   313:   Revision 1.282  2018/02/27 22:50:02  brouard
                    314:   *** empty log message ***
                    315: 
1.282     brouard   316:   Revision 1.281  2018/02/27 19:25:23  brouard
                    317:   Summary: Adding second argument for quitting
                    318: 
1.281     brouard   319:   Revision 1.280  2018/02/21 07:58:13  brouard
                    320:   Summary: 0.99r15
                    321: 
                    322:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    323: 
1.280     brouard   324:   Revision 1.279  2017/07/20 13:35:01  brouard
                    325:   Summary: temporary working
                    326: 
1.279     brouard   327:   Revision 1.278  2017/07/19 14:09:02  brouard
                    328:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    329: 
1.278     brouard   330:   Revision 1.277  2017/07/17 08:53:49  brouard
                    331:   Summary: BOM files can be read now
                    332: 
1.277     brouard   333:   Revision 1.276  2017/06/30 15:48:31  brouard
                    334:   Summary: Graphs improvements
                    335: 
1.276     brouard   336:   Revision 1.275  2017/06/30 13:39:33  brouard
                    337:   Summary: Saito's color
                    338: 
1.275     brouard   339:   Revision 1.274  2017/06/29 09:47:08  brouard
                    340:   Summary: Version 0.99r14
                    341: 
1.274     brouard   342:   Revision 1.273  2017/06/27 11:06:02  brouard
                    343:   Summary: More documentation on projections
                    344: 
1.273     brouard   345:   Revision 1.272  2017/06/27 10:22:40  brouard
                    346:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    347: 
1.272     brouard   348:   Revision 1.271  2017/06/27 10:17:50  brouard
                    349:   Summary: Some bug with rint
                    350: 
1.271     brouard   351:   Revision 1.270  2017/05/24 05:45:29  brouard
                    352:   *** empty log message ***
                    353: 
1.270     brouard   354:   Revision 1.269  2017/05/23 08:39:25  brouard
                    355:   Summary: Code into subroutine, cleanings
                    356: 
1.269     brouard   357:   Revision 1.268  2017/05/18 20:09:32  brouard
                    358:   Summary: backprojection and confidence intervals of backprevalence
                    359: 
1.268     brouard   360:   Revision 1.267  2017/05/13 10:25:05  brouard
                    361:   Summary: temporary save for backprojection
                    362: 
1.267     brouard   363:   Revision 1.266  2017/05/13 07:26:12  brouard
                    364:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    365: 
1.266     brouard   366:   Revision 1.265  2017/04/26 16:22:11  brouard
                    367:   Summary: imach 0.99r13 Some bugs fixed
                    368: 
1.265     brouard   369:   Revision 1.264  2017/04/26 06:01:29  brouard
                    370:   Summary: Labels in graphs
                    371: 
1.264     brouard   372:   Revision 1.263  2017/04/24 15:23:15  brouard
                    373:   Summary: to save
                    374: 
1.263     brouard   375:   Revision 1.262  2017/04/18 16:48:12  brouard
                    376:   *** empty log message ***
                    377: 
1.262     brouard   378:   Revision 1.261  2017/04/05 10:14:09  brouard
                    379:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    380: 
1.261     brouard   381:   Revision 1.260  2017/04/04 17:46:59  brouard
                    382:   Summary: Gnuplot indexations fixed (humm)
                    383: 
1.260     brouard   384:   Revision 1.259  2017/04/04 13:01:16  brouard
                    385:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    386: 
1.259     brouard   387:   Revision 1.258  2017/04/03 10:17:47  brouard
                    388:   Summary: Version 0.99r12
                    389: 
                    390:   Some cleanings, conformed with updated documentation.
                    391: 
1.258     brouard   392:   Revision 1.257  2017/03/29 16:53:30  brouard
                    393:   Summary: Temp
                    394: 
1.257     brouard   395:   Revision 1.256  2017/03/27 05:50:23  brouard
                    396:   Summary: Temporary
                    397: 
1.256     brouard   398:   Revision 1.255  2017/03/08 16:02:28  brouard
                    399:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    400: 
1.255     brouard   401:   Revision 1.254  2017/03/08 07:13:00  brouard
                    402:   Summary: Fixing data parameter line
                    403: 
1.254     brouard   404:   Revision 1.253  2016/12/15 11:59:41  brouard
                    405:   Summary: 0.99 in progress
                    406: 
1.253     brouard   407:   Revision 1.252  2016/09/15 21:15:37  brouard
                    408:   *** empty log message ***
                    409: 
1.252     brouard   410:   Revision 1.251  2016/09/15 15:01:13  brouard
                    411:   Summary: not working
                    412: 
1.251     brouard   413:   Revision 1.250  2016/09/08 16:07:27  brouard
                    414:   Summary: continue
                    415: 
1.250     brouard   416:   Revision 1.249  2016/09/07 17:14:18  brouard
                    417:   Summary: Starting values from frequencies
                    418: 
1.249     brouard   419:   Revision 1.248  2016/09/07 14:10:18  brouard
                    420:   *** empty log message ***
                    421: 
1.248     brouard   422:   Revision 1.247  2016/09/02 11:11:21  brouard
                    423:   *** empty log message ***
                    424: 
1.247     brouard   425:   Revision 1.246  2016/09/02 08:49:22  brouard
                    426:   *** empty log message ***
                    427: 
1.246     brouard   428:   Revision 1.245  2016/09/02 07:25:01  brouard
                    429:   *** empty log message ***
                    430: 
1.245     brouard   431:   Revision 1.244  2016/09/02 07:17:34  brouard
                    432:   *** empty log message ***
                    433: 
1.244     brouard   434:   Revision 1.243  2016/09/02 06:45:35  brouard
                    435:   *** empty log message ***
                    436: 
1.243     brouard   437:   Revision 1.242  2016/08/30 15:01:20  brouard
                    438:   Summary: Fixing a lots
                    439: 
1.242     brouard   440:   Revision 1.241  2016/08/29 17:17:25  brouard
                    441:   Summary: gnuplot problem in Back projection to fix
                    442: 
1.241     brouard   443:   Revision 1.240  2016/08/29 07:53:18  brouard
                    444:   Summary: Better
                    445: 
1.240     brouard   446:   Revision 1.239  2016/08/26 15:51:03  brouard
                    447:   Summary: Improvement in Powell output in order to copy and paste
                    448: 
                    449:   Author:
                    450: 
1.239     brouard   451:   Revision 1.238  2016/08/26 14:23:35  brouard
                    452:   Summary: Starting tests of 0.99
                    453: 
1.238     brouard   454:   Revision 1.237  2016/08/26 09:20:19  brouard
                    455:   Summary: to valgrind
                    456: 
1.237     brouard   457:   Revision 1.236  2016/08/25 10:50:18  brouard
                    458:   *** empty log message ***
                    459: 
1.236     brouard   460:   Revision 1.235  2016/08/25 06:59:23  brouard
                    461:   *** empty log message ***
                    462: 
1.235     brouard   463:   Revision 1.234  2016/08/23 16:51:20  brouard
                    464:   *** empty log message ***
                    465: 
1.234     brouard   466:   Revision 1.233  2016/08/23 07:40:50  brouard
                    467:   Summary: not working
                    468: 
1.233     brouard   469:   Revision 1.232  2016/08/22 14:20:21  brouard
                    470:   Summary: not working
                    471: 
1.232     brouard   472:   Revision 1.231  2016/08/22 07:17:15  brouard
                    473:   Summary: not working
                    474: 
1.231     brouard   475:   Revision 1.230  2016/08/22 06:55:53  brouard
                    476:   Summary: Not working
                    477: 
1.230     brouard   478:   Revision 1.229  2016/07/23 09:45:53  brouard
                    479:   Summary: Completing for func too
                    480: 
1.229     brouard   481:   Revision 1.228  2016/07/22 17:45:30  brouard
                    482:   Summary: Fixing some arrays, still debugging
                    483: 
1.227     brouard   484:   Revision 1.226  2016/07/12 18:42:34  brouard
                    485:   Summary: temp
                    486: 
1.226     brouard   487:   Revision 1.225  2016/07/12 08:40:03  brouard
                    488:   Summary: saving but not running
                    489: 
1.225     brouard   490:   Revision 1.224  2016/07/01 13:16:01  brouard
                    491:   Summary: Fixes
                    492: 
1.224     brouard   493:   Revision 1.223  2016/02/19 09:23:35  brouard
                    494:   Summary: temporary
                    495: 
1.223     brouard   496:   Revision 1.222  2016/02/17 08:14:50  brouard
                    497:   Summary: Probably last 0.98 stable version 0.98r6
                    498: 
1.222     brouard   499:   Revision 1.221  2016/02/15 23:35:36  brouard
                    500:   Summary: minor bug
                    501: 
1.220     brouard   502:   Revision 1.219  2016/02/15 00:48:12  brouard
                    503:   *** empty log message ***
                    504: 
1.219     brouard   505:   Revision 1.218  2016/02/12 11:29:23  brouard
                    506:   Summary: 0.99 Back projections
                    507: 
1.218     brouard   508:   Revision 1.217  2015/12/23 17:18:31  brouard
                    509:   Summary: Experimental backcast
                    510: 
1.217     brouard   511:   Revision 1.216  2015/12/18 17:32:11  brouard
                    512:   Summary: 0.98r4 Warning and status=-2
                    513: 
                    514:   Version 0.98r4 is now:
                    515:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    516:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    517:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    518: 
1.216     brouard   519:   Revision 1.215  2015/12/16 08:52:24  brouard
                    520:   Summary: 0.98r4 working
                    521: 
1.215     brouard   522:   Revision 1.214  2015/12/16 06:57:54  brouard
                    523:   Summary: temporary not working
                    524: 
1.214     brouard   525:   Revision 1.213  2015/12/11 18:22:17  brouard
                    526:   Summary: 0.98r4
                    527: 
1.213     brouard   528:   Revision 1.212  2015/11/21 12:47:24  brouard
                    529:   Summary: minor typo
                    530: 
1.212     brouard   531:   Revision 1.211  2015/11/21 12:41:11  brouard
                    532:   Summary: 0.98r3 with some graph of projected cross-sectional
                    533: 
                    534:   Author: Nicolas Brouard
                    535: 
1.211     brouard   536:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   537:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   538:   Summary: Adding ftolpl parameter
                    539:   Author: N Brouard
                    540: 
                    541:   We had difficulties to get smoothed confidence intervals. It was due
                    542:   to the period prevalence which wasn't computed accurately. The inner
                    543:   parameter ftolpl is now an outer parameter of the .imach parameter
                    544:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    545:   computation are long.
                    546: 
1.209     brouard   547:   Revision 1.208  2015/11/17 14:31:57  brouard
                    548:   Summary: temporary
                    549: 
1.208     brouard   550:   Revision 1.207  2015/10/27 17:36:57  brouard
                    551:   *** empty log message ***
                    552: 
1.207     brouard   553:   Revision 1.206  2015/10/24 07:14:11  brouard
                    554:   *** empty log message ***
                    555: 
1.206     brouard   556:   Revision 1.205  2015/10/23 15:50:53  brouard
                    557:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    558: 
1.205     brouard   559:   Revision 1.204  2015/10/01 16:20:26  brouard
                    560:   Summary: Some new graphs of contribution to likelihood
                    561: 
1.204     brouard   562:   Revision 1.203  2015/09/30 17:45:14  brouard
                    563:   Summary: looking at better estimation of the hessian
                    564: 
                    565:   Also a better criteria for convergence to the period prevalence And
                    566:   therefore adding the number of years needed to converge. (The
                    567:   prevalence in any alive state shold sum to one
                    568: 
1.203     brouard   569:   Revision 1.202  2015/09/22 19:45:16  brouard
                    570:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    571: 
1.202     brouard   572:   Revision 1.201  2015/09/15 17:34:58  brouard
                    573:   Summary: 0.98r0
                    574: 
                    575:   - Some new graphs like suvival functions
                    576:   - Some bugs fixed like model=1+age+V2.
                    577: 
1.201     brouard   578:   Revision 1.200  2015/09/09 16:53:55  brouard
                    579:   Summary: Big bug thanks to Flavia
                    580: 
                    581:   Even model=1+age+V2. did not work anymore
                    582: 
1.200     brouard   583:   Revision 1.199  2015/09/07 14:09:23  brouard
                    584:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    585: 
1.199     brouard   586:   Revision 1.198  2015/09/03 07:14:39  brouard
                    587:   Summary: 0.98q5 Flavia
                    588: 
1.198     brouard   589:   Revision 1.197  2015/09/01 18:24:39  brouard
                    590:   *** empty log message ***
                    591: 
1.197     brouard   592:   Revision 1.196  2015/08/18 23:17:52  brouard
                    593:   Summary: 0.98q5
                    594: 
1.196     brouard   595:   Revision 1.195  2015/08/18 16:28:39  brouard
                    596:   Summary: Adding a hack for testing purpose
                    597: 
                    598:   After reading the title, ftol and model lines, if the comment line has
                    599:   a q, starting with #q, the answer at the end of the run is quit. It
                    600:   permits to run test files in batch with ctest. The former workaround was
                    601:   $ echo q | imach foo.imach
                    602: 
1.195     brouard   603:   Revision 1.194  2015/08/18 13:32:00  brouard
                    604:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    605: 
1.194     brouard   606:   Revision 1.193  2015/08/04 07:17:42  brouard
                    607:   Summary: 0.98q4
                    608: 
1.193     brouard   609:   Revision 1.192  2015/07/16 16:49:02  brouard
                    610:   Summary: Fixing some outputs
                    611: 
1.192     brouard   612:   Revision 1.191  2015/07/14 10:00:33  brouard
                    613:   Summary: Some fixes
                    614: 
1.191     brouard   615:   Revision 1.190  2015/05/05 08:51:13  brouard
                    616:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    617: 
                    618:   Fix 1+age+.
                    619: 
1.190     brouard   620:   Revision 1.189  2015/04/30 14:45:16  brouard
                    621:   Summary: 0.98q2
                    622: 
1.189     brouard   623:   Revision 1.188  2015/04/30 08:27:53  brouard
                    624:   *** empty log message ***
                    625: 
1.188     brouard   626:   Revision 1.187  2015/04/29 09:11:15  brouard
                    627:   *** empty log message ***
                    628: 
1.187     brouard   629:   Revision 1.186  2015/04/23 12:01:52  brouard
                    630:   Summary: V1*age is working now, version 0.98q1
                    631: 
                    632:   Some codes had been disabled in order to simplify and Vn*age was
                    633:   working in the optimization phase, ie, giving correct MLE parameters,
                    634:   but, as usual, outputs were not correct and program core dumped.
                    635: 
1.186     brouard   636:   Revision 1.185  2015/03/11 13:26:42  brouard
                    637:   Summary: Inclusion of compile and links command line for Intel Compiler
                    638: 
1.185     brouard   639:   Revision 1.184  2015/03/11 11:52:39  brouard
                    640:   Summary: Back from Windows 8. Intel Compiler
                    641: 
1.184     brouard   642:   Revision 1.183  2015/03/10 20:34:32  brouard
                    643:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    644: 
                    645:   We use directest instead of original Powell test; probably no
                    646:   incidence on the results, but better justifications;
                    647:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    648:   wrong results.
                    649: 
1.183     brouard   650:   Revision 1.182  2015/02/12 08:19:57  brouard
                    651:   Summary: Trying to keep directest which seems simpler and more general
                    652:   Author: Nicolas Brouard
                    653: 
1.182     brouard   654:   Revision 1.181  2015/02/11 23:22:24  brouard
                    655:   Summary: Comments on Powell added
                    656: 
                    657:   Author:
                    658: 
1.181     brouard   659:   Revision 1.180  2015/02/11 17:33:45  brouard
                    660:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    661: 
1.180     brouard   662:   Revision 1.179  2015/01/04 09:57:06  brouard
                    663:   Summary: back to OS/X
                    664: 
1.179     brouard   665:   Revision 1.178  2015/01/04 09:35:48  brouard
                    666:   *** empty log message ***
                    667: 
1.178     brouard   668:   Revision 1.177  2015/01/03 18:40:56  brouard
                    669:   Summary: Still testing ilc32 on OSX
                    670: 
1.177     brouard   671:   Revision 1.176  2015/01/03 16:45:04  brouard
                    672:   *** empty log message ***
                    673: 
1.176     brouard   674:   Revision 1.175  2015/01/03 16:33:42  brouard
                    675:   *** empty log message ***
                    676: 
1.175     brouard   677:   Revision 1.174  2015/01/03 16:15:49  brouard
                    678:   Summary: Still in cross-compilation
                    679: 
1.174     brouard   680:   Revision 1.173  2015/01/03 12:06:26  brouard
                    681:   Summary: trying to detect cross-compilation
                    682: 
1.173     brouard   683:   Revision 1.172  2014/12/27 12:07:47  brouard
                    684:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    685: 
1.172     brouard   686:   Revision 1.171  2014/12/23 13:26:59  brouard
                    687:   Summary: Back from Visual C
                    688: 
                    689:   Still problem with utsname.h on Windows
                    690: 
1.171     brouard   691:   Revision 1.170  2014/12/23 11:17:12  brouard
                    692:   Summary: Cleaning some \%% back to %%
                    693: 
                    694:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    695: 
1.170     brouard   696:   Revision 1.169  2014/12/22 23:08:31  brouard
                    697:   Summary: 0.98p
                    698: 
                    699:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    700: 
1.169     brouard   701:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   702:   Summary: update
1.169     brouard   703: 
1.168     brouard   704:   Revision 1.167  2014/12/22 13:50:56  brouard
                    705:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    706: 
                    707:   Testing on Linux 64
                    708: 
1.167     brouard   709:   Revision 1.166  2014/12/22 11:40:47  brouard
                    710:   *** empty log message ***
                    711: 
1.166     brouard   712:   Revision 1.165  2014/12/16 11:20:36  brouard
                    713:   Summary: After compiling on Visual C
                    714: 
                    715:   * imach.c (Module): Merging 1.61 to 1.162
                    716: 
1.165     brouard   717:   Revision 1.164  2014/12/16 10:52:11  brouard
                    718:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    719: 
                    720:   * imach.c (Module): Merging 1.61 to 1.162
                    721: 
1.164     brouard   722:   Revision 1.163  2014/12/16 10:30:11  brouard
                    723:   * imach.c (Module): Merging 1.61 to 1.162
                    724: 
1.163     brouard   725:   Revision 1.162  2014/09/25 11:43:39  brouard
                    726:   Summary: temporary backup 0.99!
                    727: 
1.162     brouard   728:   Revision 1.1  2014/09/16 11:06:58  brouard
                    729:   Summary: With some code (wrong) for nlopt
                    730: 
                    731:   Author:
                    732: 
                    733:   Revision 1.161  2014/09/15 20:41:41  brouard
                    734:   Summary: Problem with macro SQR on Intel compiler
                    735: 
1.161     brouard   736:   Revision 1.160  2014/09/02 09:24:05  brouard
                    737:   *** empty log message ***
                    738: 
1.160     brouard   739:   Revision 1.159  2014/09/01 10:34:10  brouard
                    740:   Summary: WIN32
                    741:   Author: Brouard
                    742: 
1.159     brouard   743:   Revision 1.158  2014/08/27 17:11:51  brouard
                    744:   *** empty log message ***
                    745: 
1.158     brouard   746:   Revision 1.157  2014/08/27 16:26:55  brouard
                    747:   Summary: Preparing windows Visual studio version
                    748:   Author: Brouard
                    749: 
                    750:   In order to compile on Visual studio, time.h is now correct and time_t
                    751:   and tm struct should be used. difftime should be used but sometimes I
                    752:   just make the differences in raw time format (time(&now).
                    753:   Trying to suppress #ifdef LINUX
                    754:   Add xdg-open for __linux in order to open default browser.
                    755: 
1.157     brouard   756:   Revision 1.156  2014/08/25 20:10:10  brouard
                    757:   *** empty log message ***
                    758: 
1.156     brouard   759:   Revision 1.155  2014/08/25 18:32:34  brouard
                    760:   Summary: New compile, minor changes
                    761:   Author: Brouard
                    762: 
1.155     brouard   763:   Revision 1.154  2014/06/20 17:32:08  brouard
                    764:   Summary: Outputs now all graphs of convergence to period prevalence
                    765: 
1.154     brouard   766:   Revision 1.153  2014/06/20 16:45:46  brouard
                    767:   Summary: If 3 live state, convergence to period prevalence on same graph
                    768:   Author: Brouard
                    769: 
1.153     brouard   770:   Revision 1.152  2014/06/18 17:54:09  brouard
                    771:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    772: 
1.152     brouard   773:   Revision 1.151  2014/06/18 16:43:30  brouard
                    774:   *** empty log message ***
                    775: 
1.151     brouard   776:   Revision 1.150  2014/06/18 16:42:35  brouard
                    777:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    778:   Author: brouard
                    779: 
1.150     brouard   780:   Revision 1.149  2014/06/18 15:51:14  brouard
                    781:   Summary: Some fixes in parameter files errors
                    782:   Author: Nicolas Brouard
                    783: 
1.149     brouard   784:   Revision 1.148  2014/06/17 17:38:48  brouard
                    785:   Summary: Nothing new
                    786:   Author: Brouard
                    787: 
                    788:   Just a new packaging for OS/X version 0.98nS
                    789: 
1.148     brouard   790:   Revision 1.147  2014/06/16 10:33:11  brouard
                    791:   *** empty log message ***
                    792: 
1.147     brouard   793:   Revision 1.146  2014/06/16 10:20:28  brouard
                    794:   Summary: Merge
                    795:   Author: Brouard
                    796: 
                    797:   Merge, before building revised version.
                    798: 
1.146     brouard   799:   Revision 1.145  2014/06/10 21:23:15  brouard
                    800:   Summary: Debugging with valgrind
                    801:   Author: Nicolas Brouard
                    802: 
                    803:   Lot of changes in order to output the results with some covariates
                    804:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    805:   improve the code.
                    806:   No more memory valgrind error but a lot has to be done in order to
                    807:   continue the work of splitting the code into subroutines.
                    808:   Also, decodemodel has been improved. Tricode is still not
                    809:   optimal. nbcode should be improved. Documentation has been added in
                    810:   the source code.
                    811: 
1.144     brouard   812:   Revision 1.143  2014/01/26 09:45:38  brouard
                    813:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    814: 
                    815:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    816:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    817: 
1.143     brouard   818:   Revision 1.142  2014/01/26 03:57:36  brouard
                    819:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    820: 
                    821:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    822: 
1.142     brouard   823:   Revision 1.141  2014/01/26 02:42:01  brouard
                    824:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    825: 
1.141     brouard   826:   Revision 1.140  2011/09/02 10:37:54  brouard
                    827:   Summary: times.h is ok with mingw32 now.
                    828: 
1.140     brouard   829:   Revision 1.139  2010/06/14 07:50:17  brouard
                    830:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    831:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    832: 
1.139     brouard   833:   Revision 1.138  2010/04/30 18:19:40  brouard
                    834:   *** empty log message ***
                    835: 
1.138     brouard   836:   Revision 1.137  2010/04/29 18:11:38  brouard
                    837:   (Module): Checking covariates for more complex models
                    838:   than V1+V2. A lot of change to be done. Unstable.
                    839: 
1.137     brouard   840:   Revision 1.136  2010/04/26 20:30:53  brouard
                    841:   (Module): merging some libgsl code. Fixing computation
                    842:   of likelione (using inter/intrapolation if mle = 0) in order to
                    843:   get same likelihood as if mle=1.
                    844:   Some cleaning of code and comments added.
                    845: 
1.136     brouard   846:   Revision 1.135  2009/10/29 15:33:14  brouard
                    847:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    848: 
1.135     brouard   849:   Revision 1.134  2009/10/29 13:18:53  brouard
                    850:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    851: 
1.134     brouard   852:   Revision 1.133  2009/07/06 10:21:25  brouard
                    853:   just nforces
                    854: 
1.133     brouard   855:   Revision 1.132  2009/07/06 08:22:05  brouard
                    856:   Many tings
                    857: 
1.132     brouard   858:   Revision 1.131  2009/06/20 16:22:47  brouard
                    859:   Some dimensions resccaled
                    860: 
1.131     brouard   861:   Revision 1.130  2009/05/26 06:44:34  brouard
                    862:   (Module): Max Covariate is now set to 20 instead of 8. A
                    863:   lot of cleaning with variables initialized to 0. Trying to make
                    864:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    865: 
1.130     brouard   866:   Revision 1.129  2007/08/31 13:49:27  lievre
                    867:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    868: 
1.129     lievre    869:   Revision 1.128  2006/06/30 13:02:05  brouard
                    870:   (Module): Clarifications on computing e.j
                    871: 
1.128     brouard   872:   Revision 1.127  2006/04/28 18:11:50  brouard
                    873:   (Module): Yes the sum of survivors was wrong since
                    874:   imach-114 because nhstepm was no more computed in the age
                    875:   loop. Now we define nhstepma in the age loop.
                    876:   (Module): In order to speed up (in case of numerous covariates) we
                    877:   compute health expectancies (without variances) in a first step
                    878:   and then all the health expectancies with variances or standard
                    879:   deviation (needs data from the Hessian matrices) which slows the
                    880:   computation.
                    881:   In the future we should be able to stop the program is only health
                    882:   expectancies and graph are needed without standard deviations.
                    883: 
1.127     brouard   884:   Revision 1.126  2006/04/28 17:23:28  brouard
                    885:   (Module): Yes the sum of survivors was wrong since
                    886:   imach-114 because nhstepm was no more computed in the age
                    887:   loop. Now we define nhstepma in the age loop.
                    888:   Version 0.98h
                    889: 
1.126     brouard   890:   Revision 1.125  2006/04/04 15:20:31  lievre
                    891:   Errors in calculation of health expectancies. Age was not initialized.
                    892:   Forecasting file added.
                    893: 
                    894:   Revision 1.124  2006/03/22 17:13:53  lievre
                    895:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    896:   The log-likelihood is printed in the log file
                    897: 
                    898:   Revision 1.123  2006/03/20 10:52:43  brouard
                    899:   * imach.c (Module): <title> changed, corresponds to .htm file
                    900:   name. <head> headers where missing.
                    901: 
                    902:   * imach.c (Module): Weights can have a decimal point as for
                    903:   English (a comma might work with a correct LC_NUMERIC environment,
                    904:   otherwise the weight is truncated).
                    905:   Modification of warning when the covariates values are not 0 or
                    906:   1.
                    907:   Version 0.98g
                    908: 
                    909:   Revision 1.122  2006/03/20 09:45:41  brouard
                    910:   (Module): Weights can have a decimal point as for
                    911:   English (a comma might work with a correct LC_NUMERIC environment,
                    912:   otherwise the weight is truncated).
                    913:   Modification of warning when the covariates values are not 0 or
                    914:   1.
                    915:   Version 0.98g
                    916: 
                    917:   Revision 1.121  2006/03/16 17:45:01  lievre
                    918:   * imach.c (Module): Comments concerning covariates added
                    919: 
                    920:   * imach.c (Module): refinements in the computation of lli if
                    921:   status=-2 in order to have more reliable computation if stepm is
                    922:   not 1 month. Version 0.98f
                    923: 
                    924:   Revision 1.120  2006/03/16 15:10:38  lievre
                    925:   (Module): refinements in the computation of lli if
                    926:   status=-2 in order to have more reliable computation if stepm is
                    927:   not 1 month. Version 0.98f
                    928: 
                    929:   Revision 1.119  2006/03/15 17:42:26  brouard
                    930:   (Module): Bug if status = -2, the loglikelihood was
                    931:   computed as likelihood omitting the logarithm. Version O.98e
                    932: 
                    933:   Revision 1.118  2006/03/14 18:20:07  brouard
                    934:   (Module): varevsij Comments added explaining the second
                    935:   table of variances if popbased=1 .
                    936:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    937:   (Module): Function pstamp added
                    938:   (Module): Version 0.98d
                    939: 
                    940:   Revision 1.117  2006/03/14 17:16:22  brouard
                    941:   (Module): varevsij Comments added explaining the second
                    942:   table of variances if popbased=1 .
                    943:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    944:   (Module): Function pstamp added
                    945:   (Module): Version 0.98d
                    946: 
                    947:   Revision 1.116  2006/03/06 10:29:27  brouard
                    948:   (Module): Variance-covariance wrong links and
                    949:   varian-covariance of ej. is needed (Saito).
                    950: 
                    951:   Revision 1.115  2006/02/27 12:17:45  brouard
                    952:   (Module): One freematrix added in mlikeli! 0.98c
                    953: 
                    954:   Revision 1.114  2006/02/26 12:57:58  brouard
                    955:   (Module): Some improvements in processing parameter
                    956:   filename with strsep.
                    957: 
                    958:   Revision 1.113  2006/02/24 14:20:24  brouard
                    959:   (Module): Memory leaks checks with valgrind and:
                    960:   datafile was not closed, some imatrix were not freed and on matrix
                    961:   allocation too.
                    962: 
                    963:   Revision 1.112  2006/01/30 09:55:26  brouard
                    964:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    965: 
                    966:   Revision 1.111  2006/01/25 20:38:18  brouard
                    967:   (Module): Lots of cleaning and bugs added (Gompertz)
                    968:   (Module): Comments can be added in data file. Missing date values
                    969:   can be a simple dot '.'.
                    970: 
                    971:   Revision 1.110  2006/01/25 00:51:50  brouard
                    972:   (Module): Lots of cleaning and bugs added (Gompertz)
                    973: 
                    974:   Revision 1.109  2006/01/24 19:37:15  brouard
                    975:   (Module): Comments (lines starting with a #) are allowed in data.
                    976: 
                    977:   Revision 1.108  2006/01/19 18:05:42  lievre
                    978:   Gnuplot problem appeared...
                    979:   To be fixed
                    980: 
                    981:   Revision 1.107  2006/01/19 16:20:37  brouard
                    982:   Test existence of gnuplot in imach path
                    983: 
                    984:   Revision 1.106  2006/01/19 13:24:36  brouard
                    985:   Some cleaning and links added in html output
                    986: 
                    987:   Revision 1.105  2006/01/05 20:23:19  lievre
                    988:   *** empty log message ***
                    989: 
                    990:   Revision 1.104  2005/09/30 16:11:43  lievre
                    991:   (Module): sump fixed, loop imx fixed, and simplifications.
                    992:   (Module): If the status is missing at the last wave but we know
                    993:   that the person is alive, then we can code his/her status as -2
                    994:   (instead of missing=-1 in earlier versions) and his/her
                    995:   contributions to the likelihood is 1 - Prob of dying from last
                    996:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    997:   the healthy state at last known wave). Version is 0.98
                    998: 
                    999:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1000:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1001: 
                   1002:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1003:   Add the possibility to read data file including tab characters.
                   1004: 
                   1005:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1006:   Fix on curr_time
                   1007: 
                   1008:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1009:   Add version for Mac OS X. Just define UNIX in Makefile
                   1010: 
                   1011:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1012:   *** empty log message ***
                   1013: 
                   1014:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1015:   New version 0.97 . First attempt to estimate force of mortality
                   1016:   directly from the data i.e. without the need of knowing the health
                   1017:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1018:   This is the basic analysis of mortality and should be done before any
                   1019:   other analysis, in order to test if the mortality estimated from the
                   1020:   cross-longitudinal survey is different from the mortality estimated
                   1021:   from other sources like vital statistic data.
                   1022: 
                   1023:   The same imach parameter file can be used but the option for mle should be -3.
                   1024: 
1.324     brouard  1025:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1026:   former routines in order to include the new code within the former code.
                   1027: 
                   1028:   The output is very simple: only an estimate of the intercept and of
                   1029:   the slope with 95% confident intervals.
                   1030: 
                   1031:   Current limitations:
                   1032:   A) Even if you enter covariates, i.e. with the
                   1033:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1034:   B) There is no computation of Life Expectancy nor Life Table.
                   1035: 
                   1036:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1037:   Version 0.96d. Population forecasting command line is (temporarily)
                   1038:   suppressed.
                   1039: 
                   1040:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1041:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1042:   rewritten within the same printf. Workaround: many printfs.
                   1043: 
                   1044:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1045:   * imach.c (Repository):
                   1046:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1047:   matrix (cov(a12,c31) instead of numbers.
                   1048: 
                   1049:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1050:   Just cleaning
                   1051: 
                   1052:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1053:   (Module): On windows (cygwin) function asctime_r doesn't
                   1054:   exist so I changed back to asctime which exists.
                   1055:   (Module): Version 0.96b
                   1056: 
                   1057:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1058:   (Module): On windows (cygwin) function asctime_r doesn't
                   1059:   exist so I changed back to asctime which exists.
                   1060: 
                   1061:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1062:   * imach.c (Repository): Duplicated warning errors corrected.
                   1063:   (Repository): Elapsed time after each iteration is now output. It
                   1064:   helps to forecast when convergence will be reached. Elapsed time
                   1065:   is stamped in powell.  We created a new html file for the graphs
                   1066:   concerning matrix of covariance. It has extension -cov.htm.
                   1067: 
                   1068:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1069:   (Module): Some bugs corrected for windows. Also, when
                   1070:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1071:   of the covariance matrix to be input.
                   1072: 
                   1073:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1074:   (Module): Some bugs corrected for windows. Also, when
                   1075:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1076:   of the covariance matrix to be input.
                   1077: 
                   1078:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1079:   * 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.
                   1080: 
                   1081:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1082:   Version 0.96
                   1083: 
                   1084:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1085:   (Module): Change position of html and gnuplot routines and added
                   1086:   routine fileappend.
                   1087: 
                   1088:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1089:   * imach.c (Repository): Check when date of death was earlier that
                   1090:   current date of interview. It may happen when the death was just
                   1091:   prior to the death. In this case, dh was negative and likelihood
                   1092:   was wrong (infinity). We still send an "Error" but patch by
                   1093:   assuming that the date of death was just one stepm after the
                   1094:   interview.
                   1095:   (Repository): Because some people have very long ID (first column)
                   1096:   we changed int to long in num[] and we added a new lvector for
                   1097:   memory allocation. But we also truncated to 8 characters (left
                   1098:   truncation)
                   1099:   (Repository): No more line truncation errors.
                   1100: 
                   1101:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1102:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1103:   place. It differs from routine "prevalence" which may be called
                   1104:   many times. Probs is memory consuming and must be used with
                   1105:   parcimony.
                   1106:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1107: 
                   1108:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1109:   *** empty log message ***
                   1110: 
                   1111:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1112:   Add log in  imach.c and  fullversion number is now printed.
                   1113: 
                   1114: */
                   1115: /*
                   1116:    Interpolated Markov Chain
                   1117: 
                   1118:   Short summary of the programme:
                   1119:   
1.227     brouard  1120:   This program computes Healthy Life Expectancies or State-specific
                   1121:   (if states aren't health statuses) Expectancies from
                   1122:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1123: 
                   1124:   -1- a first survey ("cross") where individuals from different ages
                   1125:   are interviewed on their health status or degree of disability (in
                   1126:   the case of a health survey which is our main interest)
                   1127: 
                   1128:   -2- at least a second wave of interviews ("longitudinal") which
                   1129:   measure each change (if any) in individual health status.  Health
                   1130:   expectancies are computed from the time spent in each health state
                   1131:   according to a model. More health states you consider, more time is
                   1132:   necessary to reach the Maximum Likelihood of the parameters involved
                   1133:   in the model.  The simplest model is the multinomial logistic model
                   1134:   where pij is the probability to be observed in state j at the second
                   1135:   wave conditional to be observed in state i at the first
                   1136:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1137:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1138:   have a more complex model than "constant and age", you should modify
                   1139:   the program where the markup *Covariates have to be included here
                   1140:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1141:   convergence.
                   1142: 
                   1143:   The advantage of this computer programme, compared to a simple
                   1144:   multinomial logistic model, is clear when the delay between waves is not
                   1145:   identical for each individual. Also, if a individual missed an
                   1146:   intermediate interview, the information is lost, but taken into
                   1147:   account using an interpolation or extrapolation.  
                   1148: 
                   1149:   hPijx is the probability to be observed in state i at age x+h
                   1150:   conditional to the observed state i at age x. The delay 'h' can be
                   1151:   split into an exact number (nh*stepm) of unobserved intermediate
                   1152:   states. This elementary transition (by month, quarter,
                   1153:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1154:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1155:   and the contribution of each individual to the likelihood is simply
                   1156:   hPijx.
                   1157: 
                   1158:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1159:   of the life expectancies. It also computes the period (stable) prevalence.
                   1160: 
                   1161: Back prevalence and projections:
1.227     brouard  1162: 
                   1163:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1164:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1165:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1166:    mobilavproj)
                   1167: 
                   1168:     Computes the back prevalence limit for any combination of
                   1169:     covariate values k at any age between ageminpar and agemaxpar and
                   1170:     returns it in **bprlim. In the loops,
                   1171: 
                   1172:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1173:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1174: 
                   1175:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1176:    Computes for any combination of covariates k and any age between bage and fage 
                   1177:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1178:                        oldm=oldms;savm=savms;
1.227     brouard  1179: 
1.267     brouard  1180:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1181:      Computes the transition matrix starting at age 'age' over
                   1182:      'nhstepm*hstepm*stepm' months (i.e. until
                   1183:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1184:      nhstepm*hstepm matrices. 
                   1185: 
                   1186:      Returns p3mat[i][j][h] after calling
                   1187:      p3mat[i][j][h]=matprod2(newm,
                   1188:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1189:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1190:      oldm);
1.226     brouard  1191: 
                   1192: Important routines
                   1193: 
                   1194: - func (or funcone), computes logit (pij) distinguishing
                   1195:   o fixed variables (single or product dummies or quantitative);
                   1196:   o varying variables by:
                   1197:    (1) wave (single, product dummies, quantitative), 
                   1198:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1199:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1200:        % varying dummy (not done) or quantitative (not done);
                   1201: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1202:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1203: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1204:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1205:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1206: 
1.226     brouard  1207: 
                   1208:   
1.324     brouard  1209:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1210:            Institut national d'études démographiques, Paris.
1.126     brouard  1211:   This software have been partly granted by Euro-REVES, a concerted action
                   1212:   from the European Union.
                   1213:   It is copyrighted identically to a GNU software product, ie programme and
                   1214:   software can be distributed freely for non commercial use. Latest version
                   1215:   can be accessed at http://euroreves.ined.fr/imach .
                   1216: 
                   1217:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1218:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1219:   
                   1220:   **********************************************************************/
                   1221: /*
                   1222:   main
                   1223:   read parameterfile
                   1224:   read datafile
                   1225:   concatwav
                   1226:   freqsummary
                   1227:   if (mle >= 1)
                   1228:     mlikeli
                   1229:   print results files
                   1230:   if mle==1 
                   1231:      computes hessian
                   1232:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1233:       begin-prev-date,...
                   1234:   open gnuplot file
                   1235:   open html file
1.145     brouard  1236:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1237:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1238:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1239:     freexexit2 possible for memory heap.
                   1240: 
                   1241:   h Pij x                         | pij_nom  ficrestpij
                   1242:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1243:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1244:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1245: 
                   1246:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1247:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1248:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1249:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1250:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1251: 
1.126     brouard  1252:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1253:   health expectancies
                   1254:   Variance-covariance of DFLE
                   1255:   prevalence()
                   1256:    movingaverage()
                   1257:   varevsij() 
                   1258:   if popbased==1 varevsij(,popbased)
                   1259:   total life expectancies
                   1260:   Variance of period (stable) prevalence
                   1261:  end
                   1262: */
                   1263: 
1.187     brouard  1264: /* #define DEBUG */
                   1265: /* #define DEBUGBRENT */
1.203     brouard  1266: /* #define DEBUGLINMIN */
                   1267: /* #define DEBUGHESS */
                   1268: #define DEBUGHESSIJ
1.224     brouard  1269: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1270: #define POWELL /* Instead of NLOPT */
1.224     brouard  1271: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1272: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1273: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1274: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1275: 
                   1276: #include <math.h>
                   1277: #include <stdio.h>
                   1278: #include <stdlib.h>
                   1279: #include <string.h>
1.226     brouard  1280: #include <ctype.h>
1.159     brouard  1281: 
                   1282: #ifdef _WIN32
                   1283: #include <io.h>
1.172     brouard  1284: #include <windows.h>
                   1285: #include <tchar.h>
1.159     brouard  1286: #else
1.126     brouard  1287: #include <unistd.h>
1.159     brouard  1288: #endif
1.126     brouard  1289: 
                   1290: #include <limits.h>
                   1291: #include <sys/types.h>
1.171     brouard  1292: 
                   1293: #if defined(__GNUC__)
                   1294: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1295: #endif
                   1296: 
1.126     brouard  1297: #include <sys/stat.h>
                   1298: #include <errno.h>
1.159     brouard  1299: /* extern int errno; */
1.126     brouard  1300: 
1.157     brouard  1301: /* #ifdef LINUX */
                   1302: /* #include <time.h> */
                   1303: /* #include "timeval.h" */
                   1304: /* #else */
                   1305: /* #include <sys/time.h> */
                   1306: /* #endif */
                   1307: 
1.126     brouard  1308: #include <time.h>
                   1309: 
1.136     brouard  1310: #ifdef GSL
                   1311: #include <gsl/gsl_errno.h>
                   1312: #include <gsl/gsl_multimin.h>
                   1313: #endif
                   1314: 
1.167     brouard  1315: 
1.162     brouard  1316: #ifdef NLOPT
                   1317: #include <nlopt.h>
                   1318: typedef struct {
                   1319:   double (* function)(double [] );
                   1320: } myfunc_data ;
                   1321: #endif
                   1322: 
1.126     brouard  1323: /* #include <libintl.h> */
                   1324: /* #define _(String) gettext (String) */
                   1325: 
1.349     brouard  1326: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1327: 
                   1328: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1329: #define GNUPLOTVERSION 5.1
                   1330: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1331: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1332: #define FILENAMELENGTH 256
1.126     brouard  1333: 
                   1334: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1335: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1336: 
1.349     brouard  1337: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1338: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1339: 
                   1340: #define NINTERVMAX 8
1.144     brouard  1341: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1342: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1343: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1344: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1345: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1346: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1347: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1348: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1349: /* #define AGESUP 130 */
1.288     brouard  1350: /* #define AGESUP 150 */
                   1351: #define AGESUP 200
1.268     brouard  1352: #define AGEINF 0
1.218     brouard  1353: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1354: #define AGEBASE 40
1.194     brouard  1355: #define AGEOVERFLOW 1.e20
1.164     brouard  1356: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1357: #ifdef _WIN32
                   1358: #define DIRSEPARATOR '\\'
                   1359: #define CHARSEPARATOR "\\"
                   1360: #define ODIRSEPARATOR '/'
                   1361: #else
1.126     brouard  1362: #define DIRSEPARATOR '/'
                   1363: #define CHARSEPARATOR "/"
                   1364: #define ODIRSEPARATOR '\\'
                   1365: #endif
                   1366: 
1.352   ! brouard  1367: /* $Id: imach.c,v 1.351 2023/04/29 10:43:47 brouard Exp $ */
1.126     brouard  1368: /* $State: Exp $ */
1.196     brouard  1369: #include "version.h"
                   1370: char version[]=__IMACH_VERSION__;
1.352   ! brouard  1371: char copyright[]="April 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";
        !          1372: char fullversion[]="$Revision: 1.351 $ $Date: 2023/04/29 10:43:47 $"; 
1.126     brouard  1373: char strstart[80];
                   1374: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1375: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1376: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1377: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1378: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1379: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1380: 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  1381: 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  1382: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1383: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1384: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1385: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1386: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1387: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1388: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1389: 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  1390: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1391: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1392: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1393: 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 */
                   1394: 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 */
                   1395: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1396: 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  1397: int nsd=0; /**< Total number of single dummy variables (output) */
                   1398: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1399: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1400: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1401: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1402: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1403: int cptcov=0; /* Working variable */
1.334     brouard  1404: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1405: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1406: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1407: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1408: int nlstate=2; /* Number of live states */
                   1409: int ndeath=1; /* Number of dead states */
1.130     brouard  1410: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1411: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1412: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1413: int popbased=0;
                   1414: 
                   1415: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1416: int maxwav=0; /* Maxim number of waves */
                   1417: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1418: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1419: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1420:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1421: int mle=1, weightopt=0;
1.126     brouard  1422: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1423: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1424: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1425:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1426: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1427: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1428: 
1.130     brouard  1429: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1430: double **matprod2(); /* test */
1.126     brouard  1431: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1432: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1433: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1434: 
1.136     brouard  1435: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1436: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1437: FILE *ficlog, *ficrespow;
1.130     brouard  1438: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1439: double fretone; /* Only one call to likelihood */
1.130     brouard  1440: long ipmx=0; /* Number of contributions */
1.126     brouard  1441: double sw; /* Sum of weights */
                   1442: char filerespow[FILENAMELENGTH];
                   1443: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1444: FILE *ficresilk;
                   1445: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1446: FILE *ficresprobmorprev;
                   1447: FILE *fichtm, *fichtmcov; /* Html File */
                   1448: FILE *ficreseij;
                   1449: char filerese[FILENAMELENGTH];
                   1450: FILE *ficresstdeij;
                   1451: char fileresstde[FILENAMELENGTH];
                   1452: FILE *ficrescveij;
                   1453: char filerescve[FILENAMELENGTH];
                   1454: FILE  *ficresvij;
                   1455: char fileresv[FILENAMELENGTH];
1.269     brouard  1456: 
1.126     brouard  1457: char title[MAXLINE];
1.234     brouard  1458: char model[MAXLINE]; /**< The model line */
1.217     brouard  1459: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1460: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1461: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1462: char command[FILENAMELENGTH];
                   1463: int  outcmd=0;
                   1464: 
1.217     brouard  1465: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1466: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1467: char filelog[FILENAMELENGTH]; /* Log file */
                   1468: char filerest[FILENAMELENGTH];
                   1469: char fileregp[FILENAMELENGTH];
                   1470: char popfile[FILENAMELENGTH];
                   1471: 
                   1472: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1473: 
1.157     brouard  1474: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1475: /* struct timezone tzp; */
                   1476: /* extern int gettimeofday(); */
                   1477: struct tm tml, *gmtime(), *localtime();
                   1478: 
                   1479: extern time_t time();
                   1480: 
                   1481: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1482: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1483: time_t   rlast_btime; /* raw time */
1.157     brouard  1484: struct tm tm;
                   1485: 
1.126     brouard  1486: char strcurr[80], strfor[80];
                   1487: 
                   1488: char *endptr;
                   1489: long lval;
                   1490: double dval;
                   1491: 
                   1492: #define NR_END 1
                   1493: #define FREE_ARG char*
                   1494: #define FTOL 1.0e-10
                   1495: 
                   1496: #define NRANSI 
1.240     brouard  1497: #define ITMAX 200
                   1498: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1499: 
                   1500: #define TOL 2.0e-4 
                   1501: 
                   1502: #define CGOLD 0.3819660 
                   1503: #define ZEPS 1.0e-10 
                   1504: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1505: 
                   1506: #define GOLD 1.618034 
                   1507: #define GLIMIT 100.0 
                   1508: #define TINY 1.0e-20 
                   1509: 
                   1510: static double maxarg1,maxarg2;
                   1511: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1512: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1513:   
                   1514: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1515: #define rint(a) floor(a+0.5)
1.166     brouard  1516: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1517: #define mytinydouble 1.0e-16
1.166     brouard  1518: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1519: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1520: /* static double dsqrarg; */
                   1521: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1522: static double sqrarg;
                   1523: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1524: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1525: int agegomp= AGEGOMP;
                   1526: 
                   1527: int imx; 
                   1528: int stepm=1;
                   1529: /* Stepm, step in month: minimum step interpolation*/
                   1530: 
                   1531: int estepm;
                   1532: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1533: 
                   1534: int m,nb;
                   1535: long *num;
1.197     brouard  1536: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1537: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1538:                   covariate for which somebody answered excluding 
                   1539:                   undefined. Usually 2: 0 and 1. */
                   1540: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1541:                             covariate for which somebody answered including 
                   1542:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1543: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1544: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1545: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1546: 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  1547: double *ageexmed,*agecens;
                   1548: double dateintmean=0;
1.296     brouard  1549:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1550:   double anprojf, mprojf, jprojf;
1.126     brouard  1551: 
1.296     brouard  1552:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1553:   double anbackf, mbackf, jbackf;
                   1554:   double jintmean,mintmean,aintmean;  
1.126     brouard  1555: double *weight;
                   1556: int **s; /* Status */
1.141     brouard  1557: double *agedc;
1.145     brouard  1558: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1559:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1560:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1561: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1562: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1563: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1564: double  idx; 
                   1565: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1566: /* Some documentation */
                   1567:       /*   Design original data
                   1568:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1569:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1570:        *                                                             ntv=3     nqtv=1
1.330     brouard  1571:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1572:        * For time varying covariate, quanti or dummies
                   1573:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1574:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1575:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1576:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1577:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1578:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1579:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1580:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1581:        */
                   1582: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1583: /* 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
                   1584:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1585:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1586: */
1.349     brouard  1587: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1588: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1589: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1590:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1591:                                                                /* product without age, 3 for age and double product   */
                   1592: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1593:                                                                 /*(single or product without age), 2 dummy*/
                   1594:                                                                /* with age product, 3 quant with age product*/
                   1595: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1596: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1597: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1598: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1599: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1600: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1601: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1602: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1603: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1604: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1605: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1606: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1607: /* 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"*/
                   1608: /*  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}*/
                   1609: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>}
                   1610: /* 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}*/
                   1611: /* 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  1612: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1613: /* 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  1614: /* 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  1615: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1616: /* Type                    */
                   1617: /* V         1  2  3  4  5 */
                   1618: /*           F  F  V  V  V */
                   1619: /*           D  Q  D  D  Q */
                   1620: /*                         */
                   1621: int *TvarsD;
1.330     brouard  1622: int *TnsdVar;
1.234     brouard  1623: int *TvarsDind;
                   1624: int *TvarsQ;
                   1625: int *TvarsQind;
                   1626: 
1.318     brouard  1627: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1628: int nresult=0;
1.258     brouard  1629: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1630: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1631: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1632: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1633: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1634: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1635: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1636: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1637: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1638: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1639: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1640: 
                   1641: /* 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
                   1642:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1643:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1644: */
1.234     brouard  1645: /* 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  1646: 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 */
                   1647: 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 */
                   1648: 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 */
                   1649: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1650: 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 */
                   1651: 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  1652: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1653: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1654: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1655: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1656: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1657: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1658: 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 */
                   1659: 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  1660: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1661: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1662: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1663: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1664: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1665: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1666:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1667:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1668:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1669:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1670:       /* 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  1671: int *Tvarsel; /**< Selected covariates for output */
                   1672: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1673: 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  1674: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1675: 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  1676: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1677: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1678: int *Tage;
1.227     brouard  1679: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1680: 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  1681: 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*/ 
                   1682: 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  1683: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1684: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1685: int **Tvard;
1.330     brouard  1686: int **Tvardk;
1.227     brouard  1687: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1688: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1689: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1690:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1691:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1692: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1693: double *lsurv, *lpop, *tpop;
                   1694: 
1.231     brouard  1695: #define FD 1; /* Fixed dummy covariate */
                   1696: #define FQ 2; /* Fixed quantitative covariate */
                   1697: #define FP 3; /* Fixed product covariate */
                   1698: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1699: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1700: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1701: #define VD 10; /* Varying dummy covariate */
                   1702: #define VQ 11; /* Varying quantitative covariate */
                   1703: #define VP 12; /* Varying product covariate */
                   1704: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1705: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1706: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1707: #define APFD 16; /* Age product * fixed dummy covariate */
                   1708: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1709: #define APVD 18; /* Age product * varying dummy covariate */
                   1710: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1711: 
                   1712: #define FTYPE 1; /* Fixed covariate */
                   1713: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1714: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1715: 
                   1716: struct kmodel{
                   1717:        int maintype; /* main type */
                   1718:        int subtype; /* subtype */
                   1719: };
                   1720: struct kmodel modell[NCOVMAX];
                   1721: 
1.143     brouard  1722: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1723: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1724: 
                   1725: /**************** split *************************/
                   1726: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1727: {
                   1728:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1729:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1730:   */ 
                   1731:   char *ss;                            /* pointer */
1.186     brouard  1732:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1733: 
                   1734:   l1 = strlen(path );                  /* length of path */
                   1735:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1736:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1737:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1738:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1739:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1740:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1741:     /* get current working directory */
                   1742:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1743: #ifdef WIN32
                   1744:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1745: #else
                   1746:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1747: #endif
1.126     brouard  1748:       return( GLOCK_ERROR_GETCWD );
                   1749:     }
                   1750:     /* got dirc from getcwd*/
                   1751:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1752:   } else {                             /* strip directory from path */
1.126     brouard  1753:     ss++;                              /* after this, the filename */
                   1754:     l2 = strlen( ss );                 /* length of filename */
                   1755:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1756:     strcpy( name, ss );                /* save file name */
                   1757:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1758:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1759:     printf(" DIRC2 = %s \n",dirc);
                   1760:   }
                   1761:   /* We add a separator at the end of dirc if not exists */
                   1762:   l1 = strlen( dirc );                 /* length of directory */
                   1763:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1764:     dirc[l1] =  DIRSEPARATOR;
                   1765:     dirc[l1+1] = 0; 
                   1766:     printf(" DIRC3 = %s \n",dirc);
                   1767:   }
                   1768:   ss = strrchr( name, '.' );           /* find last / */
                   1769:   if (ss >0){
                   1770:     ss++;
                   1771:     strcpy(ext,ss);                    /* save extension */
                   1772:     l1= strlen( name);
                   1773:     l2= strlen(ss)+1;
                   1774:     strncpy( finame, name, l1-l2);
                   1775:     finame[l1-l2]= 0;
                   1776:   }
                   1777: 
                   1778:   return( 0 );                         /* we're done */
                   1779: }
                   1780: 
                   1781: 
                   1782: /******************************************/
                   1783: 
                   1784: void replace_back_to_slash(char *s, char*t)
                   1785: {
                   1786:   int i;
                   1787:   int lg=0;
                   1788:   i=0;
                   1789:   lg=strlen(t);
                   1790:   for(i=0; i<= lg; i++) {
                   1791:     (s[i] = t[i]);
                   1792:     if (t[i]== '\\') s[i]='/';
                   1793:   }
                   1794: }
                   1795: 
1.132     brouard  1796: char *trimbb(char *out, char *in)
1.137     brouard  1797: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1798:   char *s;
                   1799:   s=out;
                   1800:   while (*in != '\0'){
1.137     brouard  1801:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1802:       in++;
                   1803:     }
                   1804:     *out++ = *in++;
                   1805:   }
                   1806:   *out='\0';
                   1807:   return s;
                   1808: }
                   1809: 
1.351     brouard  1810: char *trimbtab(char *out, char *in)
                   1811: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1812:   char *s;
                   1813:   s=out;
                   1814:   while (*in != '\0'){
                   1815:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1816:       in++;
                   1817:     }
                   1818:     *out++ = *in++;
                   1819:   }
                   1820:   *out='\0';
                   1821:   return s;
                   1822: }
                   1823: 
1.187     brouard  1824: /* char *substrchaine(char *out, char *in, char *chain) */
                   1825: /* { */
                   1826: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1827: /*   char *s, *t; */
                   1828: /*   t=in;s=out; */
                   1829: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1830: /*     *out++ = *in++; */
                   1831: /*   } */
                   1832: 
                   1833: /*   /\* *in matches *chain *\/ */
                   1834: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1835: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1836: /*   } */
                   1837: /*   in--; chain--; */
                   1838: /*   while ( (*in != '\0')){ */
                   1839: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1840: /*     *out++ = *in++; */
                   1841: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1842: /*   } */
                   1843: /*   *out='\0'; */
                   1844: /*   out=s; */
                   1845: /*   return out; */
                   1846: /* } */
                   1847: char *substrchaine(char *out, char *in, char *chain)
                   1848: {
                   1849:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1850:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1851: 
                   1852:   char *strloc;
                   1853: 
1.349     brouard  1854:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1855:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1856:   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  1857:   if(strloc != NULL){ 
1.349     brouard  1858:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1859:     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)*/
                   1860:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1861:   }
1.349     brouard  1862:   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  1863:   return out;
                   1864: }
                   1865: 
                   1866: 
1.145     brouard  1867: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1868: {
1.187     brouard  1869:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1870:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1871:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1872:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1873:   */
1.160     brouard  1874:   char *s, *t;
1.145     brouard  1875:   t=in;s=in;
                   1876:   while ((*in != occ) && (*in != '\0')){
                   1877:     *alocc++ = *in++;
                   1878:   }
                   1879:   if( *in == occ){
                   1880:     *(alocc)='\0';
                   1881:     s=++in;
                   1882:   }
                   1883:  
                   1884:   if (s == t) {/* occ not found */
                   1885:     *(alocc-(in-s))='\0';
                   1886:     in=s;
                   1887:   }
                   1888:   while ( *in != '\0'){
                   1889:     *blocc++ = *in++;
                   1890:   }
                   1891: 
                   1892:   *blocc='\0';
                   1893:   return t;
                   1894: }
1.137     brouard  1895: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1896: {
1.187     brouard  1897:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1898:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1899:      gives blocc="abcdef2ghi" and alocc="j".
                   1900:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1901:   */
                   1902:   char *s, *t;
                   1903:   t=in;s=in;
                   1904:   while (*in != '\0'){
                   1905:     while( *in == occ){
                   1906:       *blocc++ = *in++;
                   1907:       s=in;
                   1908:     }
                   1909:     *blocc++ = *in++;
                   1910:   }
                   1911:   if (s == t) /* occ not found */
                   1912:     *(blocc-(in-s))='\0';
                   1913:   else
                   1914:     *(blocc-(in-s)-1)='\0';
                   1915:   in=s;
                   1916:   while ( *in != '\0'){
                   1917:     *alocc++ = *in++;
                   1918:   }
                   1919: 
                   1920:   *alocc='\0';
                   1921:   return s;
                   1922: }
                   1923: 
1.126     brouard  1924: int nbocc(char *s, char occ)
                   1925: {
                   1926:   int i,j=0;
                   1927:   int lg=20;
                   1928:   i=0;
                   1929:   lg=strlen(s);
                   1930:   for(i=0; i<= lg; i++) {
1.234     brouard  1931:     if  (s[i] == occ ) j++;
1.126     brouard  1932:   }
                   1933:   return j;
                   1934: }
                   1935: 
1.349     brouard  1936: int nboccstr(char *textin, char *chain)
                   1937: {
                   1938:   /* Counts the number of occurence of "chain"  in string textin */
                   1939:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1940:   char *strloc;
                   1941:   
                   1942:   int i,j=0;
                   1943: 
                   1944:   i=0;
                   1945: 
                   1946:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1947:   for(;;) {
                   1948:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1949:     if(strloc != NULL){
                   1950:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1951:       j++;
                   1952:     }else
                   1953:       break;
                   1954:   }
                   1955:   return j;
                   1956:   
                   1957: }
1.137     brouard  1958: /* void cutv(char *u,char *v, char*t, char occ) */
                   1959: /* { */
                   1960: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1961: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1962: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1963: /*   int i,lg,j,p=0; */
                   1964: /*   i=0; */
                   1965: /*   lg=strlen(t); */
                   1966: /*   for(j=0; j<=lg-1; j++) { */
                   1967: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1968: /*   } */
1.126     brouard  1969: 
1.137     brouard  1970: /*   for(j=0; j<p; j++) { */
                   1971: /*     (u[j] = t[j]); */
                   1972: /*   } */
                   1973: /*      u[p]='\0'; */
1.126     brouard  1974: 
1.137     brouard  1975: /*    for(j=0; j<= lg; j++) { */
                   1976: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1977: /*   } */
                   1978: /* } */
1.126     brouard  1979: 
1.160     brouard  1980: #ifdef _WIN32
                   1981: char * strsep(char **pp, const char *delim)
                   1982: {
                   1983:   char *p, *q;
                   1984:          
                   1985:   if ((p = *pp) == NULL)
                   1986:     return 0;
                   1987:   if ((q = strpbrk (p, delim)) != NULL)
                   1988:   {
                   1989:     *pp = q + 1;
                   1990:     *q = '\0';
                   1991:   }
                   1992:   else
                   1993:     *pp = 0;
                   1994:   return p;
                   1995: }
                   1996: #endif
                   1997: 
1.126     brouard  1998: /********************** nrerror ********************/
                   1999: 
                   2000: void nrerror(char error_text[])
                   2001: {
                   2002:   fprintf(stderr,"ERREUR ...\n");
                   2003:   fprintf(stderr,"%s\n",error_text);
                   2004:   exit(EXIT_FAILURE);
                   2005: }
                   2006: /*********************** vector *******************/
                   2007: double *vector(int nl, int nh)
                   2008: {
                   2009:   double *v;
                   2010:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2011:   if (!v) nrerror("allocation failure in vector");
                   2012:   return v-nl+NR_END;
                   2013: }
                   2014: 
                   2015: /************************ free vector ******************/
                   2016: void free_vector(double*v, int nl, int nh)
                   2017: {
                   2018:   free((FREE_ARG)(v+nl-NR_END));
                   2019: }
                   2020: 
                   2021: /************************ivector *******************************/
                   2022: int *ivector(long nl,long nh)
                   2023: {
                   2024:   int *v;
                   2025:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2026:   if (!v) nrerror("allocation failure in ivector");
                   2027:   return v-nl+NR_END;
                   2028: }
                   2029: 
                   2030: /******************free ivector **************************/
                   2031: void free_ivector(int *v, long nl, long nh)
                   2032: {
                   2033:   free((FREE_ARG)(v+nl-NR_END));
                   2034: }
                   2035: 
                   2036: /************************lvector *******************************/
                   2037: long *lvector(long nl,long nh)
                   2038: {
                   2039:   long *v;
                   2040:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2041:   if (!v) nrerror("allocation failure in ivector");
                   2042:   return v-nl+NR_END;
                   2043: }
                   2044: 
                   2045: /******************free lvector **************************/
                   2046: void free_lvector(long *v, long nl, long nh)
                   2047: {
                   2048:   free((FREE_ARG)(v+nl-NR_END));
                   2049: }
                   2050: 
                   2051: /******************* imatrix *******************************/
                   2052: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2053:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2054: { 
                   2055:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2056:   int **m; 
                   2057:   
                   2058:   /* allocate pointers to rows */ 
                   2059:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2060:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2061:   m += NR_END; 
                   2062:   m -= nrl; 
                   2063:   
                   2064:   
                   2065:   /* allocate rows and set pointers to them */ 
                   2066:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2067:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2068:   m[nrl] += NR_END; 
                   2069:   m[nrl] -= ncl; 
                   2070:   
                   2071:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2072:   
                   2073:   /* return pointer to array of pointers to rows */ 
                   2074:   return m; 
                   2075: } 
                   2076: 
                   2077: /****************** free_imatrix *************************/
                   2078: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2079:       int **m;
                   2080:       long nch,ncl,nrh,nrl; 
                   2081:      /* free an int matrix allocated by imatrix() */ 
                   2082: { 
                   2083:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2084:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2085: } 
                   2086: 
                   2087: /******************* matrix *******************************/
                   2088: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2089: {
                   2090:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2091:   double **m;
                   2092: 
                   2093:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2094:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2095:   m += NR_END;
                   2096:   m -= nrl;
                   2097: 
                   2098:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2099:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2100:   m[nrl] += NR_END;
                   2101:   m[nrl] -= ncl;
                   2102: 
                   2103:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2104:   return m;
1.145     brouard  2105:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2106: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2107: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2108:    */
                   2109: }
                   2110: 
                   2111: /*************************free matrix ************************/
                   2112: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2113: {
                   2114:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2115:   free((FREE_ARG)(m+nrl-NR_END));
                   2116: }
                   2117: 
                   2118: /******************* ma3x *******************************/
                   2119: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2120: {
                   2121:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2122:   double ***m;
                   2123: 
                   2124:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2125:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2126:   m += NR_END;
                   2127:   m -= nrl;
                   2128: 
                   2129:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2130:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2131:   m[nrl] += NR_END;
                   2132:   m[nrl] -= ncl;
                   2133: 
                   2134:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2135: 
                   2136:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2137:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2138:   m[nrl][ncl] += NR_END;
                   2139:   m[nrl][ncl] -= nll;
                   2140:   for (j=ncl+1; j<=nch; j++) 
                   2141:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2142:   
                   2143:   for (i=nrl+1; i<=nrh; i++) {
                   2144:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2145:     for (j=ncl+1; j<=nch; j++) 
                   2146:       m[i][j]=m[i][j-1]+nlay;
                   2147:   }
                   2148:   return m; 
                   2149:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2150:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2151:   */
                   2152: }
                   2153: 
                   2154: /*************************free ma3x ************************/
                   2155: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2156: {
                   2157:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2158:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2159:   free((FREE_ARG)(m+nrl-NR_END));
                   2160: }
                   2161: 
                   2162: /*************** function subdirf ***********/
                   2163: char *subdirf(char fileres[])
                   2164: {
                   2165:   /* Caution optionfilefiname is hidden */
                   2166:   strcpy(tmpout,optionfilefiname);
                   2167:   strcat(tmpout,"/"); /* Add to the right */
                   2168:   strcat(tmpout,fileres);
                   2169:   return tmpout;
                   2170: }
                   2171: 
                   2172: /*************** function subdirf2 ***********/
                   2173: char *subdirf2(char fileres[], char *preop)
                   2174: {
1.314     brouard  2175:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2176:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2177:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2178:   /* Caution optionfilefiname is hidden */
                   2179:   strcpy(tmpout,optionfilefiname);
                   2180:   strcat(tmpout,"/");
                   2181:   strcat(tmpout,preop);
                   2182:   strcat(tmpout,fileres);
                   2183:   return tmpout;
                   2184: }
                   2185: 
                   2186: /*************** function subdirf3 ***********/
                   2187: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2188: {
                   2189:   
                   2190:   /* Caution optionfilefiname is hidden */
                   2191:   strcpy(tmpout,optionfilefiname);
                   2192:   strcat(tmpout,"/");
                   2193:   strcat(tmpout,preop);
                   2194:   strcat(tmpout,preop2);
                   2195:   strcat(tmpout,fileres);
                   2196:   return tmpout;
                   2197: }
1.213     brouard  2198:  
                   2199: /*************** function subdirfext ***********/
                   2200: char *subdirfext(char fileres[], char *preop, char *postop)
                   2201: {
                   2202:   
                   2203:   strcpy(tmpout,preop);
                   2204:   strcat(tmpout,fileres);
                   2205:   strcat(tmpout,postop);
                   2206:   return tmpout;
                   2207: }
1.126     brouard  2208: 
1.213     brouard  2209: /*************** function subdirfext3 ***********/
                   2210: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2211: {
                   2212:   
                   2213:   /* Caution optionfilefiname is hidden */
                   2214:   strcpy(tmpout,optionfilefiname);
                   2215:   strcat(tmpout,"/");
                   2216:   strcat(tmpout,preop);
                   2217:   strcat(tmpout,fileres);
                   2218:   strcat(tmpout,postop);
                   2219:   return tmpout;
                   2220: }
                   2221:  
1.162     brouard  2222: char *asc_diff_time(long time_sec, char ascdiff[])
                   2223: {
                   2224:   long sec_left, days, hours, minutes;
                   2225:   days = (time_sec) / (60*60*24);
                   2226:   sec_left = (time_sec) % (60*60*24);
                   2227:   hours = (sec_left) / (60*60) ;
                   2228:   sec_left = (sec_left) %(60*60);
                   2229:   minutes = (sec_left) /60;
                   2230:   sec_left = (sec_left) % (60);
                   2231:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2232:   return ascdiff;
                   2233: }
                   2234: 
1.126     brouard  2235: /***************** f1dim *************************/
                   2236: extern int ncom; 
                   2237: extern double *pcom,*xicom;
                   2238: extern double (*nrfunc)(double []); 
                   2239:  
                   2240: double f1dim(double x) 
                   2241: { 
                   2242:   int j; 
                   2243:   double f;
                   2244:   double *xt; 
                   2245:  
                   2246:   xt=vector(1,ncom); 
                   2247:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2248:   f=(*nrfunc)(xt); 
                   2249:   free_vector(xt,1,ncom); 
                   2250:   return f; 
                   2251: } 
                   2252: 
                   2253: /*****************brent *************************/
                   2254: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2255: {
                   2256:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2257:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2258:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2259:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2260:    * returned function value. 
                   2261:   */
1.126     brouard  2262:   int iter; 
                   2263:   double a,b,d,etemp;
1.159     brouard  2264:   double fu=0,fv,fw,fx;
1.164     brouard  2265:   double ftemp=0.;
1.126     brouard  2266:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2267:   double e=0.0; 
                   2268:  
                   2269:   a=(ax < cx ? ax : cx); 
                   2270:   b=(ax > cx ? ax : cx); 
                   2271:   x=w=v=bx; 
                   2272:   fw=fv=fx=(*f)(x); 
                   2273:   for (iter=1;iter<=ITMAX;iter++) { 
                   2274:     xm=0.5*(a+b); 
                   2275:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2276:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2277:     printf(".");fflush(stdout);
                   2278:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2279: #ifdef DEBUGBRENT
1.126     brouard  2280:     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);
                   2281:     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);
                   2282:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2283: #endif
                   2284:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2285:       *xmin=x; 
                   2286:       return fx; 
                   2287:     } 
                   2288:     ftemp=fu;
                   2289:     if (fabs(e) > tol1) { 
                   2290:       r=(x-w)*(fx-fv); 
                   2291:       q=(x-v)*(fx-fw); 
                   2292:       p=(x-v)*q-(x-w)*r; 
                   2293:       q=2.0*(q-r); 
                   2294:       if (q > 0.0) p = -p; 
                   2295:       q=fabs(q); 
                   2296:       etemp=e; 
                   2297:       e=d; 
                   2298:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2299:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2300:       else { 
1.224     brouard  2301:                                d=p/q; 
                   2302:                                u=x+d; 
                   2303:                                if (u-a < tol2 || b-u < tol2) 
                   2304:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2305:       } 
                   2306:     } else { 
                   2307:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2308:     } 
                   2309:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2310:     fu=(*f)(u); 
                   2311:     if (fu <= fx) { 
                   2312:       if (u >= x) a=x; else b=x; 
                   2313:       SHFT(v,w,x,u) 
1.183     brouard  2314:       SHFT(fv,fw,fx,fu) 
                   2315:     } else { 
                   2316:       if (u < x) a=u; else b=u; 
                   2317:       if (fu <= fw || w == x) { 
1.224     brouard  2318:                                v=w; 
                   2319:                                w=u; 
                   2320:                                fv=fw; 
                   2321:                                fw=fu; 
1.183     brouard  2322:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2323:                                v=u; 
                   2324:                                fv=fu; 
1.183     brouard  2325:       } 
                   2326:     } 
1.126     brouard  2327:   } 
                   2328:   nrerror("Too many iterations in brent"); 
                   2329:   *xmin=x; 
                   2330:   return fx; 
                   2331: } 
                   2332: 
                   2333: /****************** mnbrak ***********************/
                   2334: 
                   2335: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2336:            double (*func)(double)) 
1.183     brouard  2337: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2338: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2339: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2340: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2341:    */
1.126     brouard  2342:   double ulim,u,r,q, dum;
                   2343:   double fu; 
1.187     brouard  2344: 
                   2345:   double scale=10.;
                   2346:   int iterscale=0;
                   2347: 
                   2348:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2349:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2350: 
                   2351: 
                   2352:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2353:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2354:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2355:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2356:   /* } */
                   2357: 
1.126     brouard  2358:   if (*fb > *fa) { 
                   2359:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2360:     SHFT(dum,*fb,*fa,dum) 
                   2361:   } 
1.126     brouard  2362:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2363:   *fc=(*func)(*cx); 
1.183     brouard  2364: #ifdef DEBUG
1.224     brouard  2365:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2366:   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  2367: #endif
1.224     brouard  2368:   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  2369:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2370:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2371:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2372:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2373:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2374:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2375:       fu=(*func)(u); 
1.163     brouard  2376: #ifdef DEBUG
                   2377:       /* f(x)=A(x-u)**2+f(u) */
                   2378:       double A, fparabu; 
                   2379:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2380:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2381:       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);
                   2382:       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  2383:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2384:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2385:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2386:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2387: #endif 
1.184     brouard  2388: #ifdef MNBRAKORIGINAL
1.183     brouard  2389: #else
1.191     brouard  2390: /*       if (fu > *fc) { */
                   2391: /* #ifdef DEBUG */
                   2392: /*       printf("mnbrak4  fu > fc \n"); */
                   2393: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2394: /* #endif */
                   2395: /*     /\* 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 *\\/  *\/ */
                   2396: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2397: /*     dum=u; /\* Shifting c and u *\/ */
                   2398: /*     u = *cx; */
                   2399: /*     *cx = dum; */
                   2400: /*     dum = fu; */
                   2401: /*     fu = *fc; */
                   2402: /*     *fc =dum; */
                   2403: /*       } else { /\* end *\/ */
                   2404: /* #ifdef DEBUG */
                   2405: /*       printf("mnbrak3  fu < fc \n"); */
                   2406: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2407: /* #endif */
                   2408: /*     dum=u; /\* Shifting c and u *\/ */
                   2409: /*     u = *cx; */
                   2410: /*     *cx = dum; */
                   2411: /*     dum = fu; */
                   2412: /*     fu = *fc; */
                   2413: /*     *fc =dum; */
                   2414: /*       } */
1.224     brouard  2415: #ifdef DEBUGMNBRAK
                   2416:                 double A, fparabu; 
                   2417:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2418:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2419:      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);
                   2420:      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  2421: #endif
1.191     brouard  2422:       dum=u; /* Shifting c and u */
                   2423:       u = *cx;
                   2424:       *cx = dum;
                   2425:       dum = fu;
                   2426:       fu = *fc;
                   2427:       *fc =dum;
1.183     brouard  2428: #endif
1.162     brouard  2429:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2430: #ifdef DEBUG
1.224     brouard  2431:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2432:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2433: #endif
1.126     brouard  2434:       fu=(*func)(u); 
                   2435:       if (fu < *fc) { 
1.183     brouard  2436: #ifdef DEBUG
1.224     brouard  2437:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2438:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2439: #endif
                   2440:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2441:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2442: #ifdef DEBUG
                   2443:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2444: #endif
                   2445:       } 
1.162     brouard  2446:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2447: #ifdef DEBUG
1.224     brouard  2448:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2449:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2450: #endif
1.126     brouard  2451:       u=ulim; 
                   2452:       fu=(*func)(u); 
1.183     brouard  2453:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2454: #ifdef DEBUG
1.224     brouard  2455:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2456:       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  2457: #endif
1.126     brouard  2458:       u=(*cx)+GOLD*(*cx-*bx); 
                   2459:       fu=(*func)(u); 
1.224     brouard  2460: #ifdef DEBUG
                   2461:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2462:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2463: #endif
1.183     brouard  2464:     } /* end tests */
1.126     brouard  2465:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2466:     SHFT(*fa,*fb,*fc,fu) 
                   2467: #ifdef DEBUG
1.224     brouard  2468:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2469:       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  2470: #endif
                   2471:   } /* 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  2472: } 
                   2473: 
                   2474: /*************** linmin ************************/
1.162     brouard  2475: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2476: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2477: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2478: the value of func at the returned location p . This is actually all accomplished by calling the
                   2479: routines mnbrak and brent .*/
1.126     brouard  2480: int ncom; 
                   2481: double *pcom,*xicom;
                   2482: double (*nrfunc)(double []); 
                   2483:  
1.224     brouard  2484: #ifdef LINMINORIGINAL
1.126     brouard  2485: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2486: #else
                   2487: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2488: #endif
1.126     brouard  2489: { 
                   2490:   double brent(double ax, double bx, double cx, 
                   2491:               double (*f)(double), double tol, double *xmin); 
                   2492:   double f1dim(double x); 
                   2493:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2494:              double *fc, double (*func)(double)); 
                   2495:   int j; 
                   2496:   double xx,xmin,bx,ax; 
                   2497:   double fx,fb,fa;
1.187     brouard  2498: 
1.203     brouard  2499: #ifdef LINMINORIGINAL
                   2500: #else
                   2501:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2502: #endif
                   2503:   
1.126     brouard  2504:   ncom=n; 
                   2505:   pcom=vector(1,n); 
                   2506:   xicom=vector(1,n); 
                   2507:   nrfunc=func; 
                   2508:   for (j=1;j<=n;j++) { 
                   2509:     pcom[j]=p[j]; 
1.202     brouard  2510:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2511:   } 
1.187     brouard  2512: 
1.203     brouard  2513: #ifdef LINMINORIGINAL
                   2514:   xx=1.;
                   2515: #else
                   2516:   axs=0.0;
                   2517:   xxs=1.;
                   2518:   do{
                   2519:     xx= xxs;
                   2520: #endif
1.187     brouard  2521:     ax=0.;
                   2522:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2523:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2524:     /* 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))   */
                   2525:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2526:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2527:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2528:     /* 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  2529: #ifdef LINMINORIGINAL
                   2530: #else
                   2531:     if (fx != fx){
1.224     brouard  2532:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2533:                        printf("|");
                   2534:                        fprintf(ficlog,"|");
1.203     brouard  2535: #ifdef DEBUGLINMIN
1.224     brouard  2536:                        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  2537: #endif
                   2538:     }
1.224     brouard  2539:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2540: #endif
                   2541:   
1.191     brouard  2542: #ifdef DEBUGLINMIN
                   2543:   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  2544:   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  2545: #endif
1.224     brouard  2546: #ifdef LINMINORIGINAL
                   2547: #else
1.317     brouard  2548:   if(fb == fx){ /* Flat function in the direction */
                   2549:     xmin=xx;
1.224     brouard  2550:     *flat=1;
1.317     brouard  2551:   }else{
1.224     brouard  2552:     *flat=0;
                   2553: #endif
                   2554:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2555:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2556:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2557:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2558:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2559:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2560: #ifdef DEBUG
1.224     brouard  2561:   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);
                   2562:   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);
                   2563: #endif
                   2564: #ifdef LINMINORIGINAL
                   2565: #else
                   2566:                        }
1.126     brouard  2567: #endif
1.191     brouard  2568: #ifdef DEBUGLINMIN
                   2569:   printf("linmin end ");
1.202     brouard  2570:   fprintf(ficlog,"linmin end ");
1.191     brouard  2571: #endif
1.126     brouard  2572:   for (j=1;j<=n;j++) { 
1.203     brouard  2573: #ifdef LINMINORIGINAL
                   2574:     xi[j] *= xmin; 
                   2575: #else
                   2576: #ifdef DEBUGLINMIN
                   2577:     if(xxs <1.0)
                   2578:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2579: #endif
                   2580:     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) */
                   2581: #ifdef DEBUGLINMIN
                   2582:     if(xxs <1.0)
                   2583:       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 );
                   2584: #endif
                   2585: #endif
1.187     brouard  2586:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2587:   } 
1.191     brouard  2588: #ifdef DEBUGLINMIN
1.203     brouard  2589:   printf("\n");
1.191     brouard  2590:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2591:   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  2592:   for (j=1;j<=n;j++) { 
1.202     brouard  2593:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2594:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2595:     if(j % ncovmodel == 0){
1.191     brouard  2596:       printf("\n");
1.202     brouard  2597:       fprintf(ficlog,"\n");
                   2598:     }
1.191     brouard  2599:   }
1.203     brouard  2600: #else
1.191     brouard  2601: #endif
1.126     brouard  2602:   free_vector(xicom,1,n); 
                   2603:   free_vector(pcom,1,n); 
                   2604: } 
                   2605: 
                   2606: 
                   2607: /*************** powell ************************/
1.162     brouard  2608: /*
1.317     brouard  2609: Minimization of a function func of n variables. Input consists in an initial starting point
                   2610: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2611: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2612: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2613: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2614: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2615:  */
1.224     brouard  2616: #ifdef LINMINORIGINAL
                   2617: #else
                   2618:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2619:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2620: #endif
1.126     brouard  2621: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2622:            double (*func)(double [])) 
                   2623: { 
1.224     brouard  2624: #ifdef LINMINORIGINAL
                   2625:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2626:              double (*func)(double [])); 
1.224     brouard  2627: #else 
1.241     brouard  2628:  void linmin(double p[], double xi[], int n, double *fret,
                   2629:             double (*func)(double []),int *flat); 
1.224     brouard  2630: #endif
1.239     brouard  2631:  int i,ibig,j,jk,k; 
1.126     brouard  2632:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2633:   double directest;
1.126     brouard  2634:   double fp,fptt;
                   2635:   double *xits;
                   2636:   int niterf, itmp;
1.349     brouard  2637:   int Bigter=0, nBigterf=1;
                   2638:   
1.126     brouard  2639:   pt=vector(1,n); 
                   2640:   ptt=vector(1,n); 
                   2641:   xit=vector(1,n); 
                   2642:   xits=vector(1,n); 
                   2643:   *fret=(*func)(p); 
                   2644:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2645:   rcurr_time = time(NULL);
                   2646:   fp=(*fret); /* Initialisation */
1.126     brouard  2647:   for (*iter=1;;++(*iter)) { 
                   2648:     ibig=0; 
                   2649:     del=0.0; 
1.157     brouard  2650:     rlast_time=rcurr_time;
1.349     brouard  2651:     rlast_btime=rcurr_time;
1.157     brouard  2652:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2653:     rcurr_time = time(NULL);  
                   2654:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2655:     /* 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); */
                   2656:     /* 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  2657:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
                   2658:     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);
                   2659:     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);
                   2660:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  2661:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2662:     for (i=1;i<=n;i++) {
1.126     brouard  2663:       fprintf(ficrespow," %.12lf", p[i]);
                   2664:     }
1.239     brouard  2665:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2666:     printf("\n#model=  1      +     age ");
                   2667:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2668:     if(nagesqr==1){
1.241     brouard  2669:        printf("  + age*age  ");
                   2670:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2671:     }
                   2672:     for(j=1;j <=ncovmodel-2;j++){
                   2673:       if(Typevar[j]==0) {
                   2674:        printf("  +      V%d  ",Tvar[j]);
                   2675:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2676:       }else if(Typevar[j]==1) {
                   2677:        printf("  +    V%d*age ",Tvar[j]);
                   2678:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2679:       }else if(Typevar[j]==2) {
                   2680:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2681:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  2682:       }else if(Typevar[j]==3) {
                   2683:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2684:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  2685:       }
                   2686:     }
1.126     brouard  2687:     printf("\n");
1.239     brouard  2688: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2689: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2690:     fprintf(ficlog,"\n");
1.239     brouard  2691:     for(i=1,jk=1; i <=nlstate; i++){
                   2692:       for(k=1; k <=(nlstate+ndeath); k++){
                   2693:        if (k != i) {
                   2694:          printf("%d%d ",i,k);
                   2695:          fprintf(ficlog,"%d%d ",i,k);
                   2696:          for(j=1; j <=ncovmodel; j++){
                   2697:            printf("%12.7f ",p[jk]);
                   2698:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2699:            jk++; 
                   2700:          }
                   2701:          printf("\n");
                   2702:          fprintf(ficlog,"\n");
                   2703:        }
                   2704:       }
                   2705:     }
1.241     brouard  2706:     if(*iter <=3 && *iter >1){
1.157     brouard  2707:       tml = *localtime(&rcurr_time);
                   2708:       strcpy(strcurr,asctime(&tml));
                   2709:       rforecast_time=rcurr_time; 
1.126     brouard  2710:       itmp = strlen(strcurr);
                   2711:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2712:        strcurr[itmp-1]='\0';
1.162     brouard  2713:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2714:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  2715:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   2716:        niterf=nBigterf*ncovmodel;
                   2717:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  2718:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2719:        forecast_time = *localtime(&rforecast_time);
                   2720:        strcpy(strfor,asctime(&forecast_time));
                   2721:        itmp = strlen(strfor);
                   2722:        if(strfor[itmp-1]=='\n')
                   2723:          strfor[itmp-1]='\0';
1.349     brouard  2724:        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);
                   2725:        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  2726:       }
                   2727:     }
1.187     brouard  2728:     for (i=1;i<=n;i++) { /* For each direction i */
                   2729:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2730:       fptt=(*fret); 
                   2731: #ifdef DEBUG
1.203     brouard  2732:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2733:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2734: #endif
1.203     brouard  2735:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2736:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2737: #ifdef LINMINORIGINAL
1.188     brouard  2738:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2739: #else
                   2740:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2741:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2742: #endif
                   2743:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2744:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2745:                                /* because that direction will be replaced unless the gain del is small */
                   2746:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2747:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2748:                                /* with the new direction. */
                   2749:                                del=fabs(fptt-(*fret)); 
                   2750:                                ibig=i; 
1.126     brouard  2751:       } 
                   2752: #ifdef DEBUG
                   2753:       printf("%d %.12e",i,(*fret));
                   2754:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2755:       for (j=1;j<=n;j++) {
1.224     brouard  2756:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2757:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2758:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2759:       }
                   2760:       for(j=1;j<=n;j++) {
1.225     brouard  2761:                                printf(" p(%d)=%.12e",j,p[j]);
                   2762:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2763:       }
                   2764:       printf("\n");
                   2765:       fprintf(ficlog,"\n");
                   2766: #endif
1.187     brouard  2767:     } /* end loop on each direction i */
                   2768:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2769:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2770:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2771:     for(j=1;j<=n;j++) {
                   2772:       if(flatdir[j] >0){
                   2773:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2774:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2775:       }
1.319     brouard  2776:       /* printf("\n"); */
                   2777:       /* fprintf(ficlog,"\n"); */
                   2778:     }
1.243     brouard  2779:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2780:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2781:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2782:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2783:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2784:       /* decreased of more than 3.84  */
                   2785:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2786:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2787:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2788:                        
1.188     brouard  2789:       /* Starting the program with initial values given by a former maximization will simply change */
                   2790:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2791:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2792:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2793: #ifdef DEBUG
                   2794:       int k[2],l;
                   2795:       k[0]=1;
                   2796:       k[1]=-1;
                   2797:       printf("Max: %.12e",(*func)(p));
                   2798:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2799:       for (j=1;j<=n;j++) {
                   2800:        printf(" %.12e",p[j]);
                   2801:        fprintf(ficlog," %.12e",p[j]);
                   2802:       }
                   2803:       printf("\n");
                   2804:       fprintf(ficlog,"\n");
                   2805:       for(l=0;l<=1;l++) {
                   2806:        for (j=1;j<=n;j++) {
                   2807:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2808:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2809:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2810:        }
                   2811:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2812:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2813:       }
                   2814: #endif
                   2815: 
                   2816:       free_vector(xit,1,n); 
                   2817:       free_vector(xits,1,n); 
                   2818:       free_vector(ptt,1,n); 
                   2819:       free_vector(pt,1,n); 
                   2820:       return; 
1.192     brouard  2821:     } /* enough precision */ 
1.240     brouard  2822:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2823:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2824:       ptt[j]=2.0*p[j]-pt[j]; 
                   2825:       xit[j]=p[j]-pt[j]; 
                   2826:       pt[j]=p[j]; 
                   2827:     } 
1.181     brouard  2828:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2829: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2830:                if (*iter <=4) {
1.225     brouard  2831: #else
                   2832: #endif
1.224     brouard  2833: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2834: #else
1.161     brouard  2835:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2836: #endif
1.162     brouard  2837:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2838:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2839:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2840:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2841:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2842:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2843:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2844:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2845:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2846:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2847:       /* mu² and del² are equal when f3=f1 */
                   2848:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2849:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2850:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2851:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2852: #ifdef NRCORIGINAL
                   2853:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2854: #else
                   2855:       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  2856:       t= t- del*SQR(fp-fptt);
1.183     brouard  2857: #endif
1.202     brouard  2858:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2859: #ifdef DEBUG
1.181     brouard  2860:       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);
                   2861:       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  2862:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2863:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2864:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2865:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2866:       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);
                   2867:       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);
                   2868: #endif
1.183     brouard  2869: #ifdef POWELLORIGINAL
                   2870:       if (t < 0.0) { /* Then we use it for new direction */
                   2871: #else
1.182     brouard  2872:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2873:                                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  2874:         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  2875:         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  2876:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2877:       } 
1.181     brouard  2878:       if (directest < 0.0) { /* Then we use it for new direction */
                   2879: #endif
1.191     brouard  2880: #ifdef DEBUGLINMIN
1.234     brouard  2881:        printf("Before linmin in direction P%d-P0\n",n);
                   2882:        for (j=1;j<=n;j++) {
                   2883:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2884:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2885:          if(j % ncovmodel == 0){
                   2886:            printf("\n");
                   2887:            fprintf(ficlog,"\n");
                   2888:          }
                   2889:        }
1.224     brouard  2890: #endif
                   2891: #ifdef LINMINORIGINAL
1.234     brouard  2892:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2893: #else
1.234     brouard  2894:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2895:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2896: #endif
1.234     brouard  2897:        
1.191     brouard  2898: #ifdef DEBUGLINMIN
1.234     brouard  2899:        for (j=1;j<=n;j++) { 
                   2900:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2901:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2902:          if(j % ncovmodel == 0){
                   2903:            printf("\n");
                   2904:            fprintf(ficlog,"\n");
                   2905:          }
                   2906:        }
1.224     brouard  2907: #endif
1.234     brouard  2908:        for (j=1;j<=n;j++) { 
                   2909:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2910:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2911:        }
1.224     brouard  2912: #ifdef LINMINORIGINAL
                   2913: #else
1.234     brouard  2914:        for (j=1, flatd=0;j<=n;j++) {
                   2915:          if(flatdir[j]>0)
                   2916:            flatd++;
                   2917:        }
                   2918:        if(flatd >0){
1.255     brouard  2919:          printf("%d flat directions: ",flatd);
                   2920:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2921:          for (j=1;j<=n;j++) { 
                   2922:            if(flatdir[j]>0){
                   2923:              printf("%d ",j);
                   2924:              fprintf(ficlog,"%d ",j);
                   2925:            }
                   2926:          }
                   2927:          printf("\n");
                   2928:          fprintf(ficlog,"\n");
1.319     brouard  2929: #ifdef FLATSUP
                   2930:           free_vector(xit,1,n); 
                   2931:           free_vector(xits,1,n); 
                   2932:           free_vector(ptt,1,n); 
                   2933:           free_vector(pt,1,n); 
                   2934:           return;
                   2935: #endif
1.234     brouard  2936:        }
1.191     brouard  2937: #endif
1.234     brouard  2938:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2939:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2940:        
1.126     brouard  2941: #ifdef DEBUG
1.234     brouard  2942:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2943:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2944:        for(j=1;j<=n;j++){
                   2945:          printf(" %lf",xit[j]);
                   2946:          fprintf(ficlog," %lf",xit[j]);
                   2947:        }
                   2948:        printf("\n");
                   2949:        fprintf(ficlog,"\n");
1.126     brouard  2950: #endif
1.192     brouard  2951:       } /* end of t or directest negative */
1.224     brouard  2952: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2953: #else
1.234     brouard  2954:       } /* end if (fptt < fp)  */
1.192     brouard  2955: #endif
1.225     brouard  2956: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2957:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2958: #else
1.224     brouard  2959: #endif
1.234     brouard  2960:                } /* loop iteration */ 
1.126     brouard  2961: } 
1.234     brouard  2962:   
1.126     brouard  2963: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2964:   
1.235     brouard  2965:   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  2966:   {
1.338     brouard  2967:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2968:      *   (and selected quantitative values in nres)
                   2969:      *  by left multiplying the unit
                   2970:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2971:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2972:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2973:      * or prevalence in state 1, prevalence in state 2, 0
                   2974:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2975:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2976:      * Output is prlim.
                   2977:      * Initial matrix pimij 
                   2978:      */
1.206     brouard  2979:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2980:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2981:   /*  0,                   0                  , 1} */
                   2982:   /*
                   2983:    * and after some iteration: */
                   2984:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2985:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2986:   /*  0,                   0                  , 1} */
                   2987:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2988:   /* {0.51571254859325999, 0.4842874514067399, */
                   2989:   /*  0.51326036147820708, 0.48673963852179264} */
                   2990:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2991:     
1.332     brouard  2992:     int i, ii,j,k, k1;
1.209     brouard  2993:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2994:   /* double **matprod2(); */ /* test */
1.218     brouard  2995:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2996:   double **newm;
1.209     brouard  2997:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2998:   int ncvloop=0;
1.288     brouard  2999:   int first=0;
1.169     brouard  3000:   
1.209     brouard  3001:   min=vector(1,nlstate);
                   3002:   max=vector(1,nlstate);
                   3003:   meandiff=vector(1,nlstate);
                   3004: 
1.218     brouard  3005:        /* Starting with matrix unity */
1.126     brouard  3006:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3007:     for (j=1;j<=nlstate+ndeath;j++){
                   3008:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3009:     }
1.169     brouard  3010:   
                   3011:   cov[1]=1.;
                   3012:   
                   3013:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  3014:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  3015:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  3016:     ncvloop++;
1.126     brouard  3017:     newm=savm;
                   3018:     /* Covariates have to be included here again */
1.138     brouard  3019:     cov[2]=agefin;
1.319     brouard  3020:      if(nagesqr==1){
                   3021:       cov[3]= agefin*agefin;
                   3022:      }
1.332     brouard  3023:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3024:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3025:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3026:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3027:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3028:        }else{
                   3029:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3030:        }
                   3031:      }/* End of loop on model equation */
                   3032:      
                   3033: /* Start of old code (replaced by a loop on position in the model equation */
                   3034:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3035:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3036:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3037:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3038:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3039:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3040:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3041:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3042:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3043:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3044:     /*    *nsd=3                              (1)  (2)           (3) */
                   3045:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3046:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3047:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3048:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3049:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3050:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3051:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3052:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3053:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3054:     /*    *TvarsDpType */
                   3055:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3056:     /*    * nsd=1              (1)           (2) */
                   3057:     /*    *TvarsD[nsd]          3             2 */
                   3058:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3059:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3060:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3061:     /*    *\/ */
                   3062:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3063:     /*   /\* 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)); *\/ */
                   3064:     /* } */
                   3065:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3066:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3067:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3068:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3069:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3070:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3071:     /*   /\* 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]); *\/ */
                   3072:     /* } */
                   3073:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3074:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3075:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3076:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3077:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3078:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3079:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3080:     /*   } */
                   3081:     /*   /\* 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]); *\/ */
                   3082:     /* } */
                   3083:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3084:     /*   /\* 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]); *\/ */
                   3085:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3086:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3087:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3088:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3089:     /*         }else{ */
                   3090:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3091:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3092:     /*         } */
                   3093:     /*   }else{ */
                   3094:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3095:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3096:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3097:     /*         }else{ */
                   3098:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3099:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3100:     /*         } */
                   3101:     /*   } */
                   3102:     /* } /\* End product without age *\/ */
                   3103: /* ENd of old code */
1.138     brouard  3104:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3105:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3106:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3107:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3108:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3109:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3110:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3111:     
1.126     brouard  3112:     savm=oldm;
                   3113:     oldm=newm;
1.209     brouard  3114: 
                   3115:     for(j=1; j<=nlstate; j++){
                   3116:       max[j]=0.;
                   3117:       min[j]=1.;
                   3118:     }
                   3119:     for(i=1;i<=nlstate;i++){
                   3120:       sumnew=0;
                   3121:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3122:       for(j=1; j<=nlstate; j++){ 
                   3123:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3124:        max[j]=FMAX(max[j],prlim[i][j]);
                   3125:        min[j]=FMIN(min[j],prlim[i][j]);
                   3126:       }
                   3127:     }
                   3128: 
1.126     brouard  3129:     maxmax=0.;
1.209     brouard  3130:     for(j=1; j<=nlstate; j++){
                   3131:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3132:       maxmax=FMAX(maxmax,meandiff[j]);
                   3133:       /* 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  3134:     } /* j loop */
1.203     brouard  3135:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3136:     /* 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  3137:     if(maxmax < ftolpl){
1.209     brouard  3138:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3139:       free_vector(min,1,nlstate);
                   3140:       free_vector(max,1,nlstate);
                   3141:       free_vector(meandiff,1,nlstate);
1.126     brouard  3142:       return prlim;
                   3143:     }
1.288     brouard  3144:   } /* agefin loop */
1.208     brouard  3145:     /* After some age loop it doesn't converge */
1.288     brouard  3146:   if(!first){
                   3147:     first=1;
                   3148:     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  3149:     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);
                   3150:   }else if (first >=1 && first <10){
                   3151:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3152:     first++;
                   3153:   }else if (first ==10){
                   3154:     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);
                   3155:     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");
                   3156:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3157:     first++;
1.288     brouard  3158:   }
                   3159: 
1.209     brouard  3160:   /* 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); */
                   3161:   free_vector(min,1,nlstate);
                   3162:   free_vector(max,1,nlstate);
                   3163:   free_vector(meandiff,1,nlstate);
1.208     brouard  3164:   
1.169     brouard  3165:   return prlim; /* should not reach here */
1.126     brouard  3166: }
                   3167: 
1.217     brouard  3168: 
                   3169:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3170: 
1.218     brouard  3171:  /* 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) */
                   3172:  /* 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  3173:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3174: {
1.264     brouard  3175:   /* 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  3176:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3177:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3178:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3179:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3180:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3181:   /* Initial matrix pimij */
                   3182:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3183:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3184:   /*  0,                   0                  , 1} */
                   3185:   /*
                   3186:    * and after some iteration: */
                   3187:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3188:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3189:   /*  0,                   0                  , 1} */
                   3190:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3191:   /* {0.51571254859325999, 0.4842874514067399, */
                   3192:   /*  0.51326036147820708, 0.48673963852179264} */
                   3193:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3194: 
1.332     brouard  3195:   int i, ii,j,k, k1;
1.247     brouard  3196:   int first=0;
1.217     brouard  3197:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3198:   /* double **matprod2(); */ /* test */
                   3199:   double **out, cov[NCOVMAX+1], **bmij();
                   3200:   double **newm;
1.218     brouard  3201:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3202:   double        **oldm, **savm;  /* for use */
                   3203: 
1.217     brouard  3204:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3205:   int ncvloop=0;
                   3206:   
                   3207:   min=vector(1,nlstate);
                   3208:   max=vector(1,nlstate);
                   3209:   meandiff=vector(1,nlstate);
                   3210: 
1.266     brouard  3211:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3212:   oldm=oldms; savm=savms;
                   3213:   
                   3214:   /* Starting with matrix unity */
                   3215:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3216:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3217:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3218:     }
                   3219:   
                   3220:   cov[1]=1.;
                   3221:   
                   3222:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3223:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3224:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3225:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3226:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3227:     ncvloop++;
1.218     brouard  3228:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3229:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3230:     /* Covariates have to be included here again */
                   3231:     cov[2]=agefin;
1.319     brouard  3232:     if(nagesqr==1){
1.217     brouard  3233:       cov[3]= agefin*agefin;;
1.319     brouard  3234:     }
1.332     brouard  3235:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3236:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3237:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3238:       }else{
1.332     brouard  3239:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3240:       }
1.332     brouard  3241:     }/* End of loop on model equation */
                   3242: 
                   3243: /* Old code */ 
                   3244: 
                   3245:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3246:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3247:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3248:     /*   /\* 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)); *\/ */
                   3249:     /* } */
                   3250:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3251:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3252:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3253:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3254:     /* /\* } *\/ */
                   3255:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3256:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3257:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3258:     /*   /\* 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]); *\/ */
                   3259:     /* } */
                   3260:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3261:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3262:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3263:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3264:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3265:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3266:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3267:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3268:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3269:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3270:     /*   } */
                   3271:     /*   /\* 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]); *\/ */
                   3272:     /* } */
                   3273:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3274:     /*   /\* 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]); *\/ */
                   3275:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3276:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3277:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3278:     /*         }else{ */
                   3279:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3280:     /*         } */
                   3281:     /*   }else{ */
                   3282:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3283:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3284:     /*         }else{ */
                   3285:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3286:     /*         } */
                   3287:     /*   } */
                   3288:     /* } */
1.217     brouard  3289:     
                   3290:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3291:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3292:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3293:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3294:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3295:                /* ij should be linked to the correct index of cov */
                   3296:                /* age and covariate values ij are in 'cov', but we need to pass
                   3297:                 * ij for the observed prevalence at age and status and covariate
                   3298:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3299:                 */
                   3300:     /* 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 *\/ */
                   3301:     /* 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 *\/ */
                   3302:     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  3303:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3304:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3305:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3306:     /*         printf("%d newm= ",i); */
                   3307:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3308:     /*           printf("%f ",newm[i][j]); */
                   3309:     /*         } */
                   3310:     /*         printf("oldm * "); */
                   3311:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3312:     /*           printf("%f ",oldm[i][j]); */
                   3313:     /*         } */
1.268     brouard  3314:     /*         printf(" bmmij "); */
1.266     brouard  3315:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3316:     /*           printf("%f ",pmmij[i][j]); */
                   3317:     /*         } */
                   3318:     /*         printf("\n"); */
                   3319:     /*   } */
                   3320:     /* } */
1.217     brouard  3321:     savm=oldm;
                   3322:     oldm=newm;
1.266     brouard  3323: 
1.217     brouard  3324:     for(j=1; j<=nlstate; j++){
                   3325:       max[j]=0.;
                   3326:       min[j]=1.;
                   3327:     }
                   3328:     for(j=1; j<=nlstate; j++){ 
                   3329:       for(i=1;i<=nlstate;i++){
1.234     brouard  3330:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3331:        bprlim[i][j]= newm[i][j];
                   3332:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3333:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3334:       }
                   3335:     }
1.218     brouard  3336:                
1.217     brouard  3337:     maxmax=0.;
                   3338:     for(i=1; i<=nlstate; i++){
1.318     brouard  3339:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3340:       maxmax=FMAX(maxmax,meandiff[i]);
                   3341:       /* 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  3342:     } /* i loop */
1.217     brouard  3343:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3344:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3345:     if(maxmax < ftolpl){
1.220     brouard  3346:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3347:       free_vector(min,1,nlstate);
                   3348:       free_vector(max,1,nlstate);
                   3349:       free_vector(meandiff,1,nlstate);
                   3350:       return bprlim;
                   3351:     }
1.288     brouard  3352:   } /* agefin loop */
1.217     brouard  3353:     /* After some age loop it doesn't converge */
1.288     brouard  3354:   if(!first){
1.247     brouard  3355:     first=1;
                   3356:     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\
                   3357: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   3358:   }
                   3359:   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  3360: 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);
                   3361:   /* 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); */
                   3362:   free_vector(min,1,nlstate);
                   3363:   free_vector(max,1,nlstate);
                   3364:   free_vector(meandiff,1,nlstate);
                   3365:   
                   3366:   return bprlim; /* should not reach here */
                   3367: }
                   3368: 
1.126     brouard  3369: /*************** transition probabilities ***************/ 
                   3370: 
                   3371: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3372: {
1.138     brouard  3373:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3374:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3375:      model to the ncovmodel covariates (including constant and age).
                   3376:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3377:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3378:      ncth covariate in the global vector x is given by the formula:
                   3379:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3380:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3381:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3382:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3383:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3384:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3385:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3386:   */
                   3387:   double s1, lnpijopii;
1.126     brouard  3388:   /*double t34;*/
1.164     brouard  3389:   int i,j, nc, ii, jj;
1.126     brouard  3390: 
1.223     brouard  3391:   for(i=1; i<= nlstate; i++){
                   3392:     for(j=1; j<i;j++){
                   3393:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3394:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3395:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3396:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3397:       }
                   3398:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3399:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3400:     }
                   3401:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3402:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3403:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3404:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3405:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3406:       }
                   3407:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3408:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3409:     }
                   3410:   }
1.218     brouard  3411:   
1.223     brouard  3412:   for(i=1; i<= nlstate; i++){
                   3413:     s1=0;
                   3414:     for(j=1; j<i; j++){
1.339     brouard  3415:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3416:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3417:     }
                   3418:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3419:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3420:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3421:     }
                   3422:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3423:     ps[i][i]=1./(s1+1.);
                   3424:     /* Computing other pijs */
                   3425:     for(j=1; j<i; j++)
1.325     brouard  3426:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3427:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3428:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3429:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3430:   } /* end i */
1.218     brouard  3431:   
1.223     brouard  3432:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3433:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3434:       ps[ii][jj]=0;
                   3435:       ps[ii][ii]=1;
                   3436:     }
                   3437:   }
1.294     brouard  3438: 
                   3439: 
1.223     brouard  3440:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3441:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3442:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3443:   /*   } */
                   3444:   /*   printf("\n "); */
                   3445:   /* } */
                   3446:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3447:   /*
                   3448:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3449:                goto end;*/
1.266     brouard  3450:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3451: }
                   3452: 
1.218     brouard  3453: /*************** backward transition probabilities ***************/ 
                   3454: 
                   3455:  /* 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 ) */
                   3456: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3457:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3458: {
1.302     brouard  3459:   /* 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  3460:    * 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  3461:    */
1.218     brouard  3462:   int i, ii, j,k;
1.222     brouard  3463:   
                   3464:   double **out, **pmij();
                   3465:   double sumnew=0.;
1.218     brouard  3466:   double agefin;
1.292     brouard  3467:   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  3468:   double **dnewm, **dsavm, **doldm;
                   3469:   double **bbmij;
                   3470:   
1.218     brouard  3471:   doldm=ddoldms; /* global pointers */
1.222     brouard  3472:   dnewm=ddnewms;
                   3473:   dsavm=ddsavms;
1.318     brouard  3474: 
                   3475:   /* Debug */
                   3476:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3477:   agefin=cov[2];
1.268     brouard  3478:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3479:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3480:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3481:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3482: 
                   3483:   /* P_x */
1.325     brouard  3484:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3485:   /* outputs pmmij which is a stochastic matrix in row */
                   3486: 
                   3487:   /* Diag(w_x) */
1.292     brouard  3488:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3489:   sumnew=0.;
1.269     brouard  3490:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3491:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3492:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3493:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3494:   }
                   3495:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3496:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3497:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3498:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3499:     }
                   3500:   }else{
                   3501:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3502:       for (j=1;j<=nlstate+ndeath;j++)
                   3503:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3504:     }
                   3505:     /* if(sumnew <0.9){ */
                   3506:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3507:     /* } */
                   3508:   }
                   3509:   k3=0.0;  /* We put the last diagonal to 0 */
                   3510:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3511:       doldm[ii][ii]= k3;
                   3512:   }
                   3513:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3514:   
1.292     brouard  3515:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3516:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3517: 
1.292     brouard  3518:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3519:   /* 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  3520:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3521:     sumnew=0.;
1.222     brouard  3522:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3523:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3524:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3525:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3526:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3527:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3528:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3529:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3530:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3531:        /* }else */
1.268     brouard  3532:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3533:     } /*End ii */
                   3534:   } /* 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 */
                   3535: 
1.292     brouard  3536:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3537:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3538:   /* end bmij */
1.266     brouard  3539:   return ps; /*pointer is unchanged */
1.218     brouard  3540: }
1.217     brouard  3541: /*************** transition probabilities ***************/ 
                   3542: 
1.218     brouard  3543: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3544: {
                   3545:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3546:      computes the probability to be observed in state j being in state i by appying the
                   3547:      model to the ncovmodel covariates (including constant and age).
                   3548:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3549:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3550:      ncth covariate in the global vector x is given by the formula:
                   3551:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3552:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3553:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3554:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3555:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3556:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3557:   */
                   3558:   double s1, lnpijopii;
                   3559:   /*double t34;*/
                   3560:   int i,j, nc, ii, jj;
                   3561: 
1.234     brouard  3562:   for(i=1; i<= nlstate; i++){
                   3563:     for(j=1; j<i;j++){
                   3564:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3565:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3566:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3567:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3568:       }
                   3569:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3570:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3571:     }
                   3572:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3573:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3574:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3575:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3576:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3577:       }
                   3578:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3579:     }
                   3580:   }
                   3581:   
                   3582:   for(i=1; i<= nlstate; i++){
                   3583:     s1=0;
                   3584:     for(j=1; j<i; j++){
                   3585:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3586:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3587:     }
                   3588:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3589:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3590:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3591:     }
                   3592:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3593:     ps[i][i]=1./(s1+1.);
                   3594:     /* Computing other pijs */
                   3595:     for(j=1; j<i; j++)
                   3596:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3597:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3598:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3599:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3600:   } /* end i */
                   3601:   
                   3602:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3603:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3604:       ps[ii][jj]=0;
                   3605:       ps[ii][ii]=1;
                   3606:     }
                   3607:   }
1.296     brouard  3608:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3609:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3610:     s1=0.;
                   3611:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3612:       s1+=ps[ii][jj];
                   3613:     }
                   3614:     for(ii=1; ii<= nlstate; ii++){
                   3615:       ps[ii][jj]=ps[ii][jj]/s1;
                   3616:     }
                   3617:   }
                   3618:   /* Transposition */
                   3619:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3620:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3621:       s1=ps[ii][jj];
                   3622:       ps[ii][jj]=ps[jj][ii];
                   3623:       ps[jj][ii]=s1;
                   3624:     }
                   3625:   }
                   3626:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3627:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3628:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3629:   /*   } */
                   3630:   /*   printf("\n "); */
                   3631:   /* } */
                   3632:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3633:   /*
                   3634:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3635:     goto end;*/
                   3636:   return ps;
1.217     brouard  3637: }
                   3638: 
                   3639: 
1.126     brouard  3640: /**************** Product of 2 matrices ******************/
                   3641: 
1.145     brouard  3642: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3643: {
                   3644:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3645:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3646:   /* in, b, out are matrice of pointers which should have been initialized 
                   3647:      before: only the contents of out is modified. The function returns
                   3648:      a pointer to pointers identical to out */
1.145     brouard  3649:   int i, j, k;
1.126     brouard  3650:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3651:     for(k=ncolol; k<=ncoloh; k++){
                   3652:       out[i][k]=0.;
                   3653:       for(j=ncl; j<=nch; j++)
                   3654:        out[i][k] +=in[i][j]*b[j][k];
                   3655:     }
1.126     brouard  3656:   return out;
                   3657: }
                   3658: 
                   3659: 
                   3660: /************* Higher Matrix Product ***************/
                   3661: 
1.235     brouard  3662: 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  3663: {
1.336     brouard  3664:   /* Already optimized with precov.
                   3665:      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  3666:      'nhstepm*hstepm*stepm' months (i.e. until
                   3667:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3668:      nhstepm*hstepm matrices. 
                   3669:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3670:      (typically every 2 years instead of every month which is too big 
                   3671:      for the memory).
                   3672:      Model is determined by parameters x and covariates have to be 
                   3673:      included manually here. 
                   3674: 
                   3675:      */
                   3676: 
1.330     brouard  3677:   int i, j, d, h, k, k1;
1.131     brouard  3678:   double **out, cov[NCOVMAX+1];
1.126     brouard  3679:   double **newm;
1.187     brouard  3680:   double agexact;
1.214     brouard  3681:   double agebegin, ageend;
1.126     brouard  3682: 
                   3683:   /* Hstepm could be zero and should return the unit matrix */
                   3684:   for (i=1;i<=nlstate+ndeath;i++)
                   3685:     for (j=1;j<=nlstate+ndeath;j++){
                   3686:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3687:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3688:     }
                   3689:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3690:   for(h=1; h <=nhstepm; h++){
                   3691:     for(d=1; d <=hstepm; d++){
                   3692:       newm=savm;
                   3693:       /* Covariates have to be included here again */
                   3694:       cov[1]=1.;
1.214     brouard  3695:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3696:       cov[2]=agexact;
1.319     brouard  3697:       if(nagesqr==1){
1.227     brouard  3698:        cov[3]= agexact*agexact;
1.319     brouard  3699:       }
1.330     brouard  3700:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3701:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3702:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3703:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3704:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3705:        }else{
                   3706:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3707:        }
                   3708:       }/* End of loop on model equation */
                   3709:        /* Old code */ 
                   3710: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3711: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3712: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3713: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3714: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3715: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3716: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3717: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3718: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3719: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3720: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3721: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3722: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3723: /*       /\* 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]])); *\/ */
                   3724: /*       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); */
                   3725: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3726: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3727: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3728: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3729: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3730: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3731: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3732: /*       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]]); */
                   3733: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3734: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3735: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3736: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3737: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3738: /*       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]); */
                   3739: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3740: 
                   3741: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3742: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3743: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3744: /*       /\* *\/ */
1.330     brouard  3745: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3746: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3747: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3748: /* /\*cptcovage=2                   1               2      *\/ */
                   3749: /* /\*Tage[k]=                      5               8      *\/  */
                   3750: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3751: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3752: /*       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]]); */
                   3753: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3754: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3755: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3756: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3757: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3758: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3759: /*       /\*   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); *\/ */
                   3760: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3761: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3762: /*       /\* } *\/ */
                   3763: /*       /\* 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]); *\/ */
                   3764: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3765: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3766: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3767: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3768: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3769: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3770: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3771: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3772: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3773:          
1.332     brouard  3774: /*       /\* 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])]); *\/ */
                   3775: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3776: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3777: /*       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]]); */
                   3778: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3779: 
                   3780: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3781: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3782: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3783: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3784: /*           /\* 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]])]; *\/ */
                   3785: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3786: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3787: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3788: /*       /\*   } *\/ */
                   3789: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3790: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3791: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3792: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3793: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3794: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3795: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3796: /*       /\*   } *\/ */
                   3797: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3798: /*     }/\*end of products *\/ */
                   3799:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3800:       /* for (k=1; k<=cptcovn;k++)  */
                   3801:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3802:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3803:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3804:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3805:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3806:       
                   3807:       
1.126     brouard  3808:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3809:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3810:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3811:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3812:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3813:       /* if((int)age == 70){ */
                   3814:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3815:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3816:       /*         printf("%d pmmij ",i); */
                   3817:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3818:       /*           printf("%f ",pmmij[i][j]); */
                   3819:       /*         } */
                   3820:       /*         printf(" oldm "); */
                   3821:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3822:       /*           printf("%f ",oldm[i][j]); */
                   3823:       /*         } */
                   3824:       /*         printf("\n"); */
                   3825:       /*       } */
                   3826:       /* } */
1.126     brouard  3827:       savm=oldm;
                   3828:       oldm=newm;
                   3829:     }
                   3830:     for(i=1; i<=nlstate+ndeath; i++)
                   3831:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3832:        po[i][j][h]=newm[i][j];
                   3833:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3834:       }
1.128     brouard  3835:     /*printf("h=%d ",h);*/
1.126     brouard  3836:   } /* end h */
1.267     brouard  3837:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3838:   return po;
                   3839: }
                   3840: 
1.217     brouard  3841: /************* Higher Back Matrix Product ***************/
1.218     brouard  3842: /* 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  3843: 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  3844: {
1.332     brouard  3845:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3846:      computes the transition matrix starting at age 'age' over
1.217     brouard  3847:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3848:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3849:      nhstepm*hstepm matrices.
                   3850:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3851:      (typically every 2 years instead of every month which is too big
1.217     brouard  3852:      for the memory).
1.218     brouard  3853:      Model is determined by parameters x and covariates have to be
1.266     brouard  3854:      included manually here. Then we use a call to bmij(x and cov)
                   3855:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3856:   */
1.217     brouard  3857: 
1.332     brouard  3858:   int i, j, d, h, k, k1;
1.266     brouard  3859:   double **out, cov[NCOVMAX+1], **bmij();
                   3860:   double **newm, ***newmm;
1.217     brouard  3861:   double agexact;
                   3862:   double agebegin, ageend;
1.222     brouard  3863:   double **oldm, **savm;
1.217     brouard  3864: 
1.266     brouard  3865:   newmm=po; /* To be saved */
                   3866:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3867:   /* Hstepm could be zero and should return the unit matrix */
                   3868:   for (i=1;i<=nlstate+ndeath;i++)
                   3869:     for (j=1;j<=nlstate+ndeath;j++){
                   3870:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3871:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3872:     }
                   3873:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3874:   for(h=1; h <=nhstepm; h++){
                   3875:     for(d=1; d <=hstepm; d++){
                   3876:       newm=savm;
                   3877:       /* Covariates have to be included here again */
                   3878:       cov[1]=1.;
1.271     brouard  3879:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3880:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3881:         /* Debug */
                   3882:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3883:       cov[2]=agexact;
1.332     brouard  3884:       if(nagesqr==1){
1.222     brouard  3885:        cov[3]= agexact*agexact;
1.332     brouard  3886:       }
                   3887:       /** New code */
                   3888:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  3889:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  3890:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3891:        }else{
1.332     brouard  3892:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3893:        }
1.332     brouard  3894:       }/* End of loop on model equation */
                   3895:       /** End of new code */
                   3896:   /** This was old code */
                   3897:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3898:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3899:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3900:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3901:       /*   /\* 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)); *\/ */
                   3902:       /* } */
                   3903:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3904:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3905:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3906:       /*       /\* 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]); *\/ */
                   3907:       /* } */
                   3908:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3909:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3910:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3911:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3912:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3913:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3914:       /*       } */
                   3915:       /*       /\* 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]); *\/ */
                   3916:       /* } */
                   3917:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3918:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3919:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3920:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3921:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3922:       /*         }else{ */
                   3923:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3924:       /*         } */
                   3925:       /*       }else{ */
                   3926:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3927:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3928:       /*         }else{ */
                   3929:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3930:       /*         } */
                   3931:       /*       } */
                   3932:       /* }                      */
                   3933:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3934:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3935: /** End of old code */
                   3936:       
1.218     brouard  3937:       /* Careful transposed matrix */
1.266     brouard  3938:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3939:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3940:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3941:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3942:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3943:       /* if((int)age == 70){ */
                   3944:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3945:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3946:       /*         printf("%d pmmij ",i); */
                   3947:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3948:       /*           printf("%f ",pmmij[i][j]); */
                   3949:       /*         } */
                   3950:       /*         printf(" oldm "); */
                   3951:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3952:       /*           printf("%f ",oldm[i][j]); */
                   3953:       /*         } */
                   3954:       /*         printf("\n"); */
                   3955:       /*       } */
                   3956:       /* } */
                   3957:       savm=oldm;
                   3958:       oldm=newm;
                   3959:     }
                   3960:     for(i=1; i<=nlstate+ndeath; i++)
                   3961:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3962:        po[i][j][h]=newm[i][j];
1.268     brouard  3963:        /* if(h==nhstepm) */
                   3964:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3965:       }
1.268     brouard  3966:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3967:   } /* end h */
1.268     brouard  3968:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3969:   return po;
                   3970: }
                   3971: 
                   3972: 
1.162     brouard  3973: #ifdef NLOPT
                   3974:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3975:   double fret;
                   3976:   double *xt;
                   3977:   int j;
                   3978:   myfunc_data *d2 = (myfunc_data *) pd;
                   3979: /* xt = (p1-1); */
                   3980:   xt=vector(1,n); 
                   3981:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3982: 
                   3983:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3984:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3985:   printf("Function = %.12lf ",fret);
                   3986:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3987:   printf("\n");
                   3988:  free_vector(xt,1,n);
                   3989:   return fret;
                   3990: }
                   3991: #endif
1.126     brouard  3992: 
                   3993: /*************** log-likelihood *************/
                   3994: double func( double *x)
                   3995: {
1.336     brouard  3996:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3997:   int ioffset=0;
1.339     brouard  3998:   int ipos=0,iposold=0,ncovv=0;
                   3999: 
1.340     brouard  4000:   double cotvarv, cotvarvold;
1.226     brouard  4001:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4002:   double **out;
                   4003:   double lli; /* Individual log likelihood */
                   4004:   int s1, s2;
1.228     brouard  4005:   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  4006: 
1.226     brouard  4007:   double bbh, survp;
                   4008:   double agexact;
1.336     brouard  4009:   double agebegin, ageend;
1.226     brouard  4010:   /*extern weight */
                   4011:   /* We are differentiating ll according to initial status */
                   4012:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4013:   /*for(i=1;i<imx;i++) 
                   4014:     printf(" %d\n",s[4][i]);
                   4015:   */
1.162     brouard  4016: 
1.226     brouard  4017:   ++countcallfunc;
1.162     brouard  4018: 
1.226     brouard  4019:   cov[1]=1.;
1.126     brouard  4020: 
1.226     brouard  4021:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4022:   ioffset=0;
1.226     brouard  4023:   if(mle==1){
                   4024:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4025:       /* Computes the values of the ncovmodel covariates of the model
                   4026:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4027:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4028:         to be observed in j being in i according to the model.
                   4029:       */
1.243     brouard  4030:       ioffset=2+nagesqr ;
1.233     brouard  4031:    /* Fixed */
1.345     brouard  4032:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  4033:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4034:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4035:        /*  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  4036:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  4037:        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  4038:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  4039:       }
1.226     brouard  4040:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  4041:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  4042:         has been calculated etc */
                   4043:       /* For an individual i, wav[i] gives the number of effective waves */
                   4044:       /* We compute the contribution to Likelihood of each effective transition
                   4045:         mw[mi][i] is real wave of the mi th effectve wave */
                   4046:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4047:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4048:         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  4049:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4050:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4051:       */
1.336     brouard  4052:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4053:       /* Wave varying (but not age varying) */
1.339     brouard  4054:        /* 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*\/ */
                   4055:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4056:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4057:        /* } */
1.340     brouard  4058:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4059:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4060:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4061:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  4062:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  4063:          }else{ /* fixed covariate */
1.345     brouard  4064:            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  4065:          }
1.339     brouard  4066:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4067:            cotvarvold=cotvarv;
                   4068:          }else{ /* A second product */
                   4069:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  4070:          }
                   4071:          iposold=ipos;
1.340     brouard  4072:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  4073:        }
1.339     brouard  4074:        /* for products of time varying to be done */
1.234     brouard  4075:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4076:          for (j=1;j<=nlstate+ndeath;j++){
                   4077:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4078:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4079:          }
1.336     brouard  4080: 
                   4081:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4082:        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  4083:        for(d=0; d<dh[mi][i]; d++){
                   4084:          newm=savm;
                   4085:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4086:          cov[2]=agexact;
                   4087:          if(nagesqr==1)
                   4088:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  4089:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4090:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4091:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4092:          /*   else */
                   4093:          /*     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) *\/  */
                   4094:          /* } */
                   4095:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4096:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4097:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4098:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4099:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4100:            }else{ /* fixed covariate */
                   4101:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4102:            }
                   4103:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4104:              cotvarvold=cotvarv;
                   4105:            }else{ /* A second product */
                   4106:              cotvarv=cotvarv*cotvarvold;
                   4107:            }
                   4108:            iposold=ipos;
                   4109:            cov[ioffset+ipos]=cotvarv*agexact;
                   4110:            /* For products */
1.234     brouard  4111:          }
1.349     brouard  4112:          
1.234     brouard  4113:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4114:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4115:          savm=oldm;
                   4116:          oldm=newm;
                   4117:        } /* end mult */
                   4118:        
                   4119:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4120:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4121:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4122:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4123:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4124:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4125:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4126:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4127:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4128:                                 * -stepm/2 to stepm/2 .
                   4129:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4130:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4131:                                 */
1.234     brouard  4132:        s1=s[mw[mi][i]][i];
                   4133:        s2=s[mw[mi+1][i]][i];
                   4134:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4135:        /* bias bh is positive if real duration
                   4136:         * is higher than the multiple of stepm and negative otherwise.
                   4137:         */
                   4138:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4139:        if( s2 > nlstate){ 
                   4140:          /* i.e. if s2 is a death state and if the date of death is known 
                   4141:             then the contribution to the likelihood is the probability to 
                   4142:             die between last step unit time and current  step unit time, 
                   4143:             which is also equal to probability to die before dh 
                   4144:             minus probability to die before dh-stepm . 
                   4145:             In version up to 0.92 likelihood was computed
                   4146:             as if date of death was unknown. Death was treated as any other
                   4147:             health state: the date of the interview describes the actual state
                   4148:             and not the date of a change in health state. The former idea was
                   4149:             to consider that at each interview the state was recorded
                   4150:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4151:             introduced the exact date of death then we should have modified
                   4152:             the contribution of an exact death to the likelihood. This new
                   4153:             contribution is smaller and very dependent of the step unit
                   4154:             stepm. It is no more the probability to die between last interview
                   4155:             and month of death but the probability to survive from last
                   4156:             interview up to one month before death multiplied by the
                   4157:             probability to die within a month. Thanks to Chris
                   4158:             Jackson for correcting this bug.  Former versions increased
                   4159:             mortality artificially. The bad side is that we add another loop
                   4160:             which slows down the processing. The difference can be up to 10%
                   4161:             lower mortality.
                   4162:          */
                   4163:          /* If, at the beginning of the maximization mostly, the
                   4164:             cumulative probability or probability to be dead is
                   4165:             constant (ie = 1) over time d, the difference is equal to
                   4166:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4167:             s1 at precedent wave, to be dead a month before current
                   4168:             wave is equal to probability, being at state s1 at
                   4169:             precedent wave, to be dead at mont of the current
                   4170:             wave. Then the observed probability (that this person died)
                   4171:             is null according to current estimated parameter. In fact,
                   4172:             it should be very low but not zero otherwise the log go to
                   4173:             infinity.
                   4174:          */
1.183     brouard  4175: /* #ifdef INFINITYORIGINAL */
                   4176: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4177: /* #else */
                   4178: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4179: /*         lli=log(mytinydouble); */
                   4180: /*       else */
                   4181: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4182: /* #endif */
1.226     brouard  4183:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4184:          
1.226     brouard  4185:        } else if  ( s2==-1 ) { /* alive */
                   4186:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4187:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4188:          /*survp += out[s1][j]; */
                   4189:          lli= log(survp);
                   4190:        }
1.336     brouard  4191:        /* else if  (s2==-4) {  */
                   4192:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4193:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4194:        /*   lli= log(survp);  */
                   4195:        /* }  */
                   4196:        /* else if  (s2==-5) {  */
                   4197:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4198:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4199:        /*   lli= log(survp);  */
                   4200:        /* }  */
1.226     brouard  4201:        else{
                   4202:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4203:          /*  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 */
                   4204:        } 
                   4205:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4206:        /*if(lli ==000.0)*/
1.340     brouard  4207:        /* 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  4208:        ipmx +=1;
                   4209:        sw += weight[i];
                   4210:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4211:        /* if (lli < log(mytinydouble)){ */
                   4212:        /*   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); */
                   4213:        /*   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]); */
                   4214:        /* } */
                   4215:       } /* end of wave */
                   4216:     } /* end of individual */
                   4217:   }  else if(mle==2){
                   4218:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4219:       ioffset=2+nagesqr ;
                   4220:       for (k=1; k<=ncovf;k++)
                   4221:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4222:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4223:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4224:          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  4225:        }
1.226     brouard  4226:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4227:          for (j=1;j<=nlstate+ndeath;j++){
                   4228:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4229:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4230:          }
                   4231:        for(d=0; d<=dh[mi][i]; d++){
                   4232:          newm=savm;
                   4233:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4234:          cov[2]=agexact;
                   4235:          if(nagesqr==1)
                   4236:            cov[3]= agexact*agexact;
                   4237:          for (kk=1; kk<=cptcovage;kk++) {
                   4238:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4239:          }
                   4240:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4241:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4242:          savm=oldm;
                   4243:          oldm=newm;
                   4244:        } /* end mult */
                   4245:       
                   4246:        s1=s[mw[mi][i]][i];
                   4247:        s2=s[mw[mi+1][i]][i];
                   4248:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4249:        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 */
                   4250:        ipmx +=1;
                   4251:        sw += weight[i];
                   4252:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4253:       } /* end of wave */
                   4254:     } /* end of individual */
                   4255:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4256:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4257:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4258:       for(mi=1; mi<= wav[i]-1; mi++){
                   4259:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4260:          for (j=1;j<=nlstate+ndeath;j++){
                   4261:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4262:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4263:          }
                   4264:        for(d=0; d<dh[mi][i]; d++){
                   4265:          newm=savm;
                   4266:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4267:          cov[2]=agexact;
                   4268:          if(nagesqr==1)
                   4269:            cov[3]= agexact*agexact;
                   4270:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4271:            if(!FixedV[Tvar[Tage[kk]]])
                   4272:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4273:            else
1.341     brouard  4274:              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  4275:          }
                   4276:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4277:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4278:          savm=oldm;
                   4279:          oldm=newm;
                   4280:        } /* end mult */
                   4281:       
                   4282:        s1=s[mw[mi][i]][i];
                   4283:        s2=s[mw[mi+1][i]][i];
                   4284:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4285:        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 */
                   4286:        ipmx +=1;
                   4287:        sw += weight[i];
                   4288:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4289:       } /* end of wave */
                   4290:     } /* end of individual */
                   4291:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4292:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4293:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4294:       for(mi=1; mi<= wav[i]-1; mi++){
                   4295:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4296:          for (j=1;j<=nlstate+ndeath;j++){
                   4297:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4298:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4299:          }
                   4300:        for(d=0; d<dh[mi][i]; d++){
                   4301:          newm=savm;
                   4302:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4303:          cov[2]=agexact;
                   4304:          if(nagesqr==1)
                   4305:            cov[3]= agexact*agexact;
                   4306:          for (kk=1; kk<=cptcovage;kk++) {
                   4307:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4308:          }
1.126     brouard  4309:        
1.226     brouard  4310:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4311:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4312:          savm=oldm;
                   4313:          oldm=newm;
                   4314:        } /* end mult */
                   4315:       
                   4316:        s1=s[mw[mi][i]][i];
                   4317:        s2=s[mw[mi+1][i]][i];
                   4318:        if( s2 > nlstate){ 
                   4319:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4320:        } else if  ( s2==-1 ) { /* alive */
                   4321:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4322:            survp += out[s1][j];
                   4323:          lli= log(survp);
                   4324:        }else{
                   4325:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4326:        }
                   4327:        ipmx +=1;
                   4328:        sw += weight[i];
                   4329:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  4330:        /* 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  4331:       } /* end of wave */
                   4332:     } /* end of individual */
                   4333:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4334:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4335:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4336:       for(mi=1; mi<= wav[i]-1; mi++){
                   4337:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4338:          for (j=1;j<=nlstate+ndeath;j++){
                   4339:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4340:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4341:          }
                   4342:        for(d=0; d<dh[mi][i]; d++){
                   4343:          newm=savm;
                   4344:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4345:          cov[2]=agexact;
                   4346:          if(nagesqr==1)
                   4347:            cov[3]= agexact*agexact;
                   4348:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4349:            if(!FixedV[Tvar[Tage[kk]]])
                   4350:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4351:            else
1.341     brouard  4352:              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  4353:          }
1.126     brouard  4354:        
1.226     brouard  4355:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4356:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4357:          savm=oldm;
                   4358:          oldm=newm;
                   4359:        } /* end mult */
                   4360:       
                   4361:        s1=s[mw[mi][i]][i];
                   4362:        s2=s[mw[mi+1][i]][i];
                   4363:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4364:        ipmx +=1;
                   4365:        sw += weight[i];
                   4366:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4367:        /*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]);*/
                   4368:       } /* end of wave */
                   4369:     } /* end of individual */
                   4370:   } /* End of if */
                   4371:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4372:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4373:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4374:   return -l;
1.126     brouard  4375: }
                   4376: 
                   4377: /*************** log-likelihood *************/
                   4378: double funcone( double *x)
                   4379: {
1.228     brouard  4380:   /* Same as func but slower because of a lot of printf and if */
1.349     brouard  4381:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
1.228     brouard  4382:   int ioffset=0;
1.339     brouard  4383:   int ipos=0,iposold=0,ncovv=0;
                   4384: 
1.340     brouard  4385:   double cotvarv, cotvarvold;
1.131     brouard  4386:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4387:   double **out;
                   4388:   double lli; /* Individual log likelihood */
                   4389:   double llt;
                   4390:   int s1, s2;
1.228     brouard  4391:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4392: 
1.126     brouard  4393:   double bbh, survp;
1.187     brouard  4394:   double agexact;
1.214     brouard  4395:   double agebegin, ageend;
1.126     brouard  4396:   /*extern weight */
                   4397:   /* We are differentiating ll according to initial status */
                   4398:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4399:   /*for(i=1;i<imx;i++) 
                   4400:     printf(" %d\n",s[4][i]);
                   4401:   */
                   4402:   cov[1]=1.;
                   4403: 
                   4404:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4405:   ioffset=0;
                   4406:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4407:     /* Computes the values of the ncovmodel covariates of the model
                   4408:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4409:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4410:        to be observed in j being in i according to the model.
                   4411:     */
1.243     brouard  4412:     /* ioffset=2+nagesqr+cptcovage; */
                   4413:     ioffset=2+nagesqr;
1.232     brouard  4414:     /* Fixed */
1.224     brouard  4415:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4416:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  4417:     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  4418:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4419:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4420:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4421:       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  4422: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4423: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4424: /*    cov[2+6]=covar[2][i]; V2  */
                   4425: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4426: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4427: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4428: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4429: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4430: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4431:     }
1.336     brouard  4432:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4433:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4434:         has been calculated etc */
                   4435:       /* For an individual i, wav[i] gives the number of effective waves */
                   4436:       /* We compute the contribution to Likelihood of each effective transition
                   4437:         mw[mi][i] is real wave of the mi th effectve wave */
                   4438:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4439:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4440:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4441:       */
                   4442:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4443:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4444:     /*   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?)*\/ */
                   4445:     /* } */
1.231     brouard  4446:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4447:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4448:     /* } */
1.225     brouard  4449:     
1.233     brouard  4450: 
                   4451:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4452:       /* 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 */
                   4453:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4454:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4455:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4456:       /* } */
                   4457:       
                   4458:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4459:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4460:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4461:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4462:       /* We need the position of the time varying or product in the model */
                   4463:       /* 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 */            
                   4464:       /* TvarVV gives the variable name */
1.340     brouard  4465:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4466:       *      k=         1   2     3     4         5        6        7       8        9
                   4467:       *  varying            1     2                                 3       4        5
                   4468:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  4469:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4470:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4471:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4472:       */
1.345     brouard  4473:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  4474:        * 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  4475:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  4476:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4477:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4478:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4479:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4480:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4481:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4482:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4483:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4484:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4485:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4486:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4487:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4488:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4489:        *                  12       13      14      15       16
                   4490:        *                    17        18         19        20         21
                   4491:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4492:        *                   2       3        4       6        7
                   4493:        *                     9         11          12        13         14            
                   4494:        * cptcovage=5+5 total of covariates with age 
                   4495:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4496:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4497:        *3 Tage[cptcovage] age*V3*V2=6  
                   4498:        *3                age*V2=12         13      14      15       16
                   4499:        *3                age*V6*V3=18      19    20   21
                   4500:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4501:        *     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
                   4502:        * 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
                   4503:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4504:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4505:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4506:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4507:        * 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
                   4508:        * Tvar=                {2, 3, 4, 6, 7,
                   4509:        *                       9, 10, 11, 12, 13, 14,
                   4510:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4511:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4512:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4513:        *                  2, 2, 2, 2, 2, 2,
                   4514:        * 3                3, 2, 2, 2, 2, 2,
                   4515:        *                  1, 1, 1, 1, 1, 
                   4516:        *                  3, 3, 3, 3, 3}
                   4517:        * 3                 2, 3, 3, 3, 3}
                   4518:        * 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
                   4519:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4520:        * 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}
                   4521:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4522:        * cptcovprod=11 (6+5)
                   4523:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4524:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4525:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4526:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4527:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4528:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4529:        * cptcovdageprod=5  for gnuplot printing
                   4530:        * cptcovprodvage=6 
                   4531:        * ncova=15           1        2       3       4       5
                   4532:        *                      6 7        8 9      10 11        12 13     14 15
                   4533:        * TvarA              2        3       4       6       7
                   4534:        *                      6 2        6 7       7 3          6 4       7 4
                   4535:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  4536:        * ncovf            1     2      3
1.349     brouard  4537:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4538:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4539:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4540:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4541:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4542:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4543:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4544:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4545:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4546:        * 3 cptcovprodvage=6
                   4547:        * 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
                   4548:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4549:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
                   4550:        * TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
                   4551:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4552:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4553:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4554:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4555:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4556:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4557:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4558:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  4559:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  4560:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4561:        *                   2, 3, 4, 6, 7,
                   4562:        *                     6, 8, 9, 10, 11}
1.345     brouard  4563:        * TvarFind[itv]                        0      0       0
                   4564:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   4565:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4566:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4567:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  4568:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  4569:        */
                   4570: 
1.349     brouard  4571:       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 */
                   4572:        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  4573:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  4574:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4575:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4576:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.340     brouard  4577:        }else{ /* fixed covariate */
1.345     brouard  4578:          /* 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  4579:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.340     brouard  4580:        }
1.339     brouard  4581:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4582:          cotvarvold=cotvarv;
                   4583:        }else{ /* A second product */
                   4584:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4585:        }
                   4586:        iposold=ipos;
1.340     brouard  4587:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4588:        /* For products */
                   4589:       }
                   4590:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4591:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4592:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4593:       /*       /\*           1  2   3      4      5                         *\/ */
                   4594:       /*       /\*itv           1                                           *\/ */
                   4595:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4596:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4597:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4598:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4599:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4600:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4601:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4602:       /*       /\* 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]); *\/ */
                   4603:       /* } */
1.232     brouard  4604:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4605:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4606:       /*       /\* 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]); *\/ */
                   4607:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4608:       /* } */
1.126     brouard  4609:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4610:        for (j=1;j<=nlstate+ndeath;j++){
                   4611:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4612:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4613:        }
1.214     brouard  4614:       
                   4615:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4616:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4617:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4618:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4619:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4620:          and mw[mi+1][i]. dh depends on stepm.*/
                   4621:        newm=savm;
1.247     brouard  4622:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4623:        cov[2]=agexact;
                   4624:        if(nagesqr==1)
                   4625:          cov[3]= agexact*agexact;
1.349     brouard  4626:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4627:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4628:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4629:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4630:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4631:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4632:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4633:          }else{ /* fixed covariate */
                   4634:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4635:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4636:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4637:          }
                   4638:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4639:            cotvarvold=cotvarv;
                   4640:          }else{ /* A second product */
                   4641:            /* printf("DEBUG * \n"); */
                   4642:            cotvarv=cotvarv*cotvarvold;
                   4643:          }
                   4644:          iposold=ipos;
                   4645:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4646:          cov[ioffset+ipos]=cotvarv*agexact;
                   4647:          /* For products */
1.242     brouard  4648:        }
1.349     brouard  4649: 
1.242     brouard  4650:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4651:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4652:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4653:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4654:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4655:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4656:        savm=oldm;
                   4657:        oldm=newm;
1.126     brouard  4658:       } /* end mult */
1.336     brouard  4659:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4660:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4661:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4662:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4663:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4664:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4665:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4666:         * probability in order to take into account the bias as a fraction of the way
                   4667:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4668:                                 * -stepm/2 to stepm/2 .
                   4669:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4670:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4671:                                 */
1.126     brouard  4672:       s1=s[mw[mi][i]][i];
                   4673:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4674:       /* if(s2==-1){ */
1.268     brouard  4675:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4676:       /*       /\* exit(1); *\/ */
                   4677:       /* } */
1.126     brouard  4678:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4679:       /* bias is positive if real duration
                   4680:        * is higher than the multiple of stepm and negative otherwise.
                   4681:        */
                   4682:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4683:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4684:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4685:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4686:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4687:        lli= log(survp);
1.126     brouard  4688:       }else if (mle==1){
1.242     brouard  4689:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4690:       } else if(mle==2){
1.242     brouard  4691:        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  4692:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4693:        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  4694:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4695:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4696:       } else{  /* mle=0 back to 1 */
1.242     brouard  4697:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4698:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4699:       } /* End of if */
                   4700:       ipmx +=1;
                   4701:       sw += weight[i];
                   4702:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4703:       /* Printing covariates values for each contribution for checking */
1.343     brouard  4704:       /* 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  4705:       if(globpr){
1.246     brouard  4706:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4707:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4708:                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  4709:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  4710:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4711:        /* %11.6f %11.6f %11.6f ", \ */
                   4712:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4713:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4714:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4715:          llt +=ll[k]*gipmx/gsw;
                   4716:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4717:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4718:        }
1.343     brouard  4719:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4720:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4721:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  4722:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4723:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4724:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4725:        }
                   4726:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4727:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4728:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4729:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4730:            /* printf(" %g",cov[ioffset+ipos]); */
                   4731:          }else{
                   4732:            fprintf(ficresilk,"*");
                   4733:            /* printf("*"); */
1.342     brouard  4734:          }
1.343     brouard  4735:          iposold=ipos;
                   4736:        }
1.349     brouard  4737:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   4738:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   4739:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   4740:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   4741:        /*   }else{ */
                   4742:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4743:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   4744:        /*   } */
                   4745:        /* } */
                   4746:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4747:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4748:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4749:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4750:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4751:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4752:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4753:          }else{ /* fixed covariate */
                   4754:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4755:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   4756:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4757:          }
                   4758:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4759:            cotvarvold=cotvarv;
                   4760:          }else{ /* A second product */
                   4761:            /* printf("DEBUG * \n"); */
                   4762:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  4763:          }
1.349     brouard  4764:          cotvarv=cotvarv*agexact;
                   4765:          fprintf(ficresilk," %g*age",cotvarv);
                   4766:          iposold=ipos;
                   4767:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4768:          cov[ioffset+ipos]=cotvarv;
                   4769:          /* For products */
1.343     brouard  4770:        }
                   4771:        /* printf("\n"); */
1.342     brouard  4772:        /* } /\*  End debugILK *\/ */
                   4773:        fprintf(ficresilk,"\n");
                   4774:       } /* End if globpr */
1.335     brouard  4775:     } /* end of wave */
                   4776:   } /* end of individual */
                   4777:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4778: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4779:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4780:   if(globpr==0){ /* First time we count the contributions and weights */
                   4781:     gipmx=ipmx;
                   4782:     gsw=sw;
                   4783:   }
1.343     brouard  4784:   return -l;
1.126     brouard  4785: }
                   4786: 
                   4787: 
                   4788: /*************** function likelione ***********/
1.292     brouard  4789: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4790: {
                   4791:   /* This routine should help understanding what is done with 
                   4792:      the selection of individuals/waves and
                   4793:      to check the exact contribution to the likelihood.
                   4794:      Plotting could be done.
1.342     brouard  4795:   */
                   4796:   void pstamp(FILE *ficres);
1.343     brouard  4797:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4798: 
                   4799:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4800:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4801:     strcat(fileresilk,fileresu);
1.126     brouard  4802:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4803:       printf("Problem with resultfile: %s\n", fileresilk);
                   4804:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4805:     }
1.342     brouard  4806:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4807:     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");
                   4808:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4809:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4810:     for(k=1; k<=nlstate; k++) 
                   4811:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4812:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4813: 
                   4814:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4815:       for(kf=1;kf <= ncovf; kf++){
                   4816:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4817:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4818:       }
                   4819:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  4820:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4821:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4822:          /* printf(" %d",ipos); */
                   4823:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4824:        }else{
                   4825:          /* printf("*"); */
                   4826:          fprintf(ficresilk,"*");
1.343     brouard  4827:        }
1.342     brouard  4828:        iposold=ipos;
                   4829:       }
                   4830:       for (kk=1; kk<=cptcovage;kk++) {
                   4831:        if(!FixedV[Tvar[Tage[kk]]]){
                   4832:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4833:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4834:        }else{
                   4835:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4836:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4837:        }
                   4838:       }
                   4839:     /* } /\* End if debugILK *\/ */
                   4840:     /* printf("\n"); */
                   4841:     fprintf(ficresilk,"\n");
                   4842:   } /* End glogpri */
1.126     brouard  4843: 
1.292     brouard  4844:   *fretone=(*func)(p);
1.126     brouard  4845:   if(*globpri !=0){
                   4846:     fclose(ficresilk);
1.205     brouard  4847:     if (mle ==0)
                   4848:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4849:     else if(mle >=1)
                   4850:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4851:     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  4852:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4853:       
1.207     brouard  4854:     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  4855: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4856:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  4857: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   4858:     
                   4859:     for (k=1; k<= nlstate ; k++) {
                   4860:       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 \
                   4861: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4862:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  4863:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   4864:         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]]);
                   4865:         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);
                   4866:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  4867:       }
                   4868:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   4869:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   4870:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4871:        /* 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]); */
                   4872:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4873:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   4874:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   4875:          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)  */
                   4876:            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> \
                   4877: <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);
                   4878:          } /* End only for dummies time varying (single?) */
                   4879:        }else{ /* Useless product */
                   4880:          /* printf("*"); */
                   4881:          /* fprintf(ficresilk,"*"); */ 
                   4882:        }
                   4883:        iposold=ipos;
                   4884:       } /* For each time varying covariate */
                   4885:     } /* End loop on states */
                   4886: 
                   4887: /*     if(debugILK){ */
                   4888: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   4889: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   4890: /*     for (k=1; k<= nlstate ; k++) { */
                   4891: /*       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> \ */
                   4892: /* <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]]); */
                   4893: /*     } */
                   4894: /*       } */
                   4895: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   4896: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   4897: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   4898: /*     /\* 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]); *\/ */
                   4899: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   4900: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   4901: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   4902: /*       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)  *\/ */
                   4903: /*         for (k=1; k<= nlstate ; k++) { */
                   4904: /*           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> \ */
                   4905: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   4906: /*         } /\* End state *\/ */
                   4907: /*       } /\* End only for dummies time varying (single?) *\/ */
                   4908: /*     }else{ /\* Useless product *\/ */
                   4909: /*       /\* printf("*"); *\/ */
                   4910: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   4911: /*     } */
                   4912: /*     iposold=ipos; */
                   4913: /*       } /\* For each time varying covariate *\/ */
                   4914: /*     }/\* End debugILK *\/ */
1.207     brouard  4915:     fflush(fichtm);
1.343     brouard  4916:   }/* End globpri */
1.126     brouard  4917:   return;
                   4918: }
                   4919: 
                   4920: 
                   4921: /*********** Maximum Likelihood Estimation ***************/
                   4922: 
                   4923: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4924: {
1.319     brouard  4925:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4926:   double **xi;
                   4927:   double fret;
                   4928:   double fretone; /* Only one call to likelihood */
                   4929:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4930: 
                   4931: #ifdef NLOPT
                   4932:   int creturn;
                   4933:   nlopt_opt opt;
                   4934:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4935:   double *lb;
                   4936:   double minf; /* the minimum objective value, upon return */
                   4937:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4938:   myfunc_data dinst, *d = &dinst;
                   4939: #endif
                   4940: 
                   4941: 
1.126     brouard  4942:   xi=matrix(1,npar,1,npar);
                   4943:   for (i=1;i<=npar;i++)
                   4944:     for (j=1;j<=npar;j++)
                   4945:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4946:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4947:   strcpy(filerespow,"POW_"); 
1.126     brouard  4948:   strcat(filerespow,fileres);
                   4949:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4950:     printf("Problem with resultfile: %s\n", filerespow);
                   4951:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4952:   }
                   4953:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4954:   for (i=1;i<=nlstate;i++)
                   4955:     for(j=1;j<=nlstate+ndeath;j++)
                   4956:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4957:   fprintf(ficrespow,"\n");
1.162     brouard  4958: #ifdef POWELL
1.319     brouard  4959: #ifdef LINMINORIGINAL
                   4960: #else /* LINMINORIGINAL */
                   4961:   
                   4962:   flatdir=ivector(1,npar); 
                   4963:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4964: #endif /*LINMINORIGINAL */
                   4965: 
                   4966: #ifdef FLATSUP
                   4967:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4968:   /* reorganizing p by suppressing flat directions */
                   4969:   for(i=1, jk=1; i <=nlstate; i++){
                   4970:     for(k=1; k <=(nlstate+ndeath); k++){
                   4971:       if (k != i) {
                   4972:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4973:         if(flatdir[jk]==1){
                   4974:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4975:         }
                   4976:         for(j=1; j <=ncovmodel; j++){
                   4977:           printf("%12.7f ",p[jk]);
                   4978:           jk++; 
                   4979:         }
                   4980:         printf("\n");
                   4981:       }
                   4982:     }
                   4983:   }
                   4984: /* skipping */
                   4985:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4986:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4987:     for(k=1; k <=(nlstate+ndeath); k++){
                   4988:       if (k != i) {
                   4989:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4990:         if(flatdir[jk]==1){
                   4991:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4992:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4993:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4994:             /*q[jjk]=p[jk];*/
                   4995:           }
                   4996:         }else{
                   4997:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4998:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4999:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5000:             /*q[jjk]=p[jk];*/
                   5001:           }
                   5002:         }
                   5003:         printf("\n");
                   5004:       }
                   5005:       fflush(stdout);
                   5006:     }
                   5007:   }
                   5008:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5009: #else  /* FLATSUP */
1.126     brouard  5010:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  5011: #endif  /* FLATSUP */
                   5012: 
                   5013: #ifdef LINMINORIGINAL
                   5014: #else
                   5015:       free_ivector(flatdir,1,npar); 
                   5016: #endif  /* LINMINORIGINAL*/
                   5017: #endif /* POWELL */
1.126     brouard  5018: 
1.162     brouard  5019: #ifdef NLOPT
                   5020: #ifdef NEWUOA
                   5021:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5022: #else
                   5023:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5024: #endif
                   5025:   lb=vector(0,npar-1);
                   5026:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5027:   nlopt_set_lower_bounds(opt, lb);
                   5028:   nlopt_set_initial_step1(opt, 0.1);
                   5029:   
                   5030:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5031:   d->function = func;
                   5032:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5033:   nlopt_set_min_objective(opt, myfunc, d);
                   5034:   nlopt_set_xtol_rel(opt, ftol);
                   5035:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5036:     printf("nlopt failed! %d\n",creturn); 
                   5037:   }
                   5038:   else {
                   5039:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5040:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5041:     iter=1; /* not equal */
                   5042:   }
                   5043:   nlopt_destroy(opt);
                   5044: #endif
1.319     brouard  5045: #ifdef FLATSUP
                   5046:   /* npared = npar -flatd/ncovmodel; */
                   5047:   /* xired= matrix(1,npared,1,npared); */
                   5048:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5049:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5050:   /* free_matrix(xire,1,npared,1,npared); */
                   5051: #else  /* FLATSUP */
                   5052: #endif /* FLATSUP */
1.126     brouard  5053:   free_matrix(xi,1,npar,1,npar);
                   5054:   fclose(ficrespow);
1.203     brouard  5055:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5056:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  5057:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  5058: 
                   5059: }
                   5060: 
                   5061: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  5062: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  5063: {
                   5064:   double  **a,**y,*x,pd;
1.203     brouard  5065:   /* double **hess; */
1.164     brouard  5066:   int i, j;
1.126     brouard  5067:   int *indx;
                   5068: 
                   5069:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  5070:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  5071:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5072:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5073:   double gompertz(double p[]);
1.203     brouard  5074:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  5075: 
                   5076:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5077:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5078:   for (i=1;i<=npar;i++){
1.203     brouard  5079:     printf("%d-",i);fflush(stdout);
                   5080:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  5081:    
                   5082:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5083:     
                   5084:     /*  printf(" %f ",p[i]);
                   5085:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5086:   }
                   5087:   
                   5088:   for (i=1;i<=npar;i++) {
                   5089:     for (j=1;j<=npar;j++)  {
                   5090:       if (j>i) { 
1.203     brouard  5091:        printf(".%d-%d",i,j);fflush(stdout);
                   5092:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5093:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  5094:        
                   5095:        hess[j][i]=hess[i][j];    
                   5096:        /*printf(" %lf ",hess[i][j]);*/
                   5097:       }
                   5098:     }
                   5099:   }
                   5100:   printf("\n");
                   5101:   fprintf(ficlog,"\n");
                   5102: 
                   5103:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5104:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5105:   
                   5106:   a=matrix(1,npar,1,npar);
                   5107:   y=matrix(1,npar,1,npar);
                   5108:   x=vector(1,npar);
                   5109:   indx=ivector(1,npar);
                   5110:   for (i=1;i<=npar;i++)
                   5111:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5112:   ludcmp(a,npar,indx,&pd);
                   5113: 
                   5114:   for (j=1;j<=npar;j++) {
                   5115:     for (i=1;i<=npar;i++) x[i]=0;
                   5116:     x[j]=1;
                   5117:     lubksb(a,npar,indx,x);
                   5118:     for (i=1;i<=npar;i++){ 
                   5119:       matcov[i][j]=x[i];
                   5120:     }
                   5121:   }
                   5122: 
                   5123:   printf("\n#Hessian matrix#\n");
                   5124:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5125:   for (i=1;i<=npar;i++) { 
                   5126:     for (j=1;j<=npar;j++) { 
1.203     brouard  5127:       printf("%.6e ",hess[i][j]);
                   5128:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  5129:     }
                   5130:     printf("\n");
                   5131:     fprintf(ficlog,"\n");
                   5132:   }
                   5133: 
1.203     brouard  5134:   /* printf("\n#Covariance matrix#\n"); */
                   5135:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5136:   /* for (i=1;i<=npar;i++) {  */
                   5137:   /*   for (j=1;j<=npar;j++) {  */
                   5138:   /*     printf("%.6e ",matcov[i][j]); */
                   5139:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5140:   /*   } */
                   5141:   /*   printf("\n"); */
                   5142:   /*   fprintf(ficlog,"\n"); */
                   5143:   /* } */
                   5144: 
1.126     brouard  5145:   /* Recompute Inverse */
1.203     brouard  5146:   /* for (i=1;i<=npar;i++) */
                   5147:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5148:   /* ludcmp(a,npar,indx,&pd); */
                   5149: 
                   5150:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5151: 
                   5152:   /* for (j=1;j<=npar;j++) { */
                   5153:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5154:   /*   x[j]=1; */
                   5155:   /*   lubksb(a,npar,indx,x); */
                   5156:   /*   for (i=1;i<=npar;i++){  */
                   5157:   /*     y[i][j]=x[i]; */
                   5158:   /*     printf("%.3e ",y[i][j]); */
                   5159:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5160:   /*   } */
                   5161:   /*   printf("\n"); */
                   5162:   /*   fprintf(ficlog,"\n"); */
                   5163:   /* } */
                   5164: 
                   5165:   /* Verifying the inverse matrix */
                   5166: #ifdef DEBUGHESS
                   5167:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  5168: 
1.203     brouard  5169:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5170:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  5171: 
                   5172:   for (j=1;j<=npar;j++) {
                   5173:     for (i=1;i<=npar;i++){ 
1.203     brouard  5174:       printf("%.2f ",y[i][j]);
                   5175:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  5176:     }
                   5177:     printf("\n");
                   5178:     fprintf(ficlog,"\n");
                   5179:   }
1.203     brouard  5180: #endif
1.126     brouard  5181: 
                   5182:   free_matrix(a,1,npar,1,npar);
                   5183:   free_matrix(y,1,npar,1,npar);
                   5184:   free_vector(x,1,npar);
                   5185:   free_ivector(indx,1,npar);
1.203     brouard  5186:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  5187: 
                   5188: 
                   5189: }
                   5190: 
                   5191: /*************** hessian matrix ****************/
                   5192: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  5193: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  5194:   int i;
                   5195:   int l=1, lmax=20;
1.203     brouard  5196:   double k1,k2, res, fx;
1.132     brouard  5197:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  5198:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5199:   int k=0,kmax=10;
                   5200:   double l1;
                   5201: 
                   5202:   fx=func(x);
                   5203:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  5204:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  5205:     l1=pow(10,l);
                   5206:     delts=delt;
                   5207:     for(k=1 ; k <kmax; k=k+1){
                   5208:       delt = delta*(l1*k);
                   5209:       p2[theta]=x[theta] +delt;
1.145     brouard  5210:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  5211:       p2[theta]=x[theta]-delt;
                   5212:       k2=func(p2)-fx;
                   5213:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  5214:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  5215:       
1.203     brouard  5216: #ifdef DEBUGHESSII
1.126     brouard  5217:       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);
                   5218:       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);
                   5219: #endif
                   5220:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5221:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5222:        k=kmax;
                   5223:       }
                   5224:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  5225:        k=kmax; l=lmax*10;
1.126     brouard  5226:       }
                   5227:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5228:        delts=delt;
                   5229:       }
1.203     brouard  5230:     } /* End loop k */
1.126     brouard  5231:   }
                   5232:   delti[theta]=delts;
                   5233:   return res; 
                   5234:   
                   5235: }
                   5236: 
1.203     brouard  5237: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  5238: {
                   5239:   int i;
1.164     brouard  5240:   int l=1, lmax=20;
1.126     brouard  5241:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5242:   double p2[MAXPARM+1];
1.203     brouard  5243:   int k, kmax=1;
                   5244:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5245: 
                   5246:   int firstime=0;
1.203     brouard  5247:   
1.126     brouard  5248:   fx=func(x);
1.203     brouard  5249:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5250:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5251:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5252:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5253:     k1=func(p2)-fx;
                   5254:   
1.203     brouard  5255:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5256:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5257:     k2=func(p2)-fx;
                   5258:   
1.203     brouard  5259:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5260:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5261:     k3=func(p2)-fx;
                   5262:   
1.203     brouard  5263:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5264:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5265:     k4=func(p2)-fx;
1.203     brouard  5266:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5267:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5268:       firstime=1;
1.203     brouard  5269:       kmax=kmax+10;
1.208     brouard  5270:     }
                   5271:     if(kmax >=10 || firstime ==1){
1.246     brouard  5272:       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);
                   5273:       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  5274:       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);
                   5275:       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);
                   5276:     }
                   5277: #ifdef DEBUGHESSIJ
                   5278:     v1=hess[thetai][thetai];
                   5279:     v2=hess[thetaj][thetaj];
                   5280:     cv12=res;
                   5281:     /* Computing eigen value of Hessian matrix */
                   5282:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5283:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5284:     if ((lc2 <0) || (lc1 <0) ){
                   5285:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5286:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5287:       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);
                   5288:       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);
                   5289:     }
1.126     brouard  5290: #endif
                   5291:   }
                   5292:   return res;
                   5293: }
                   5294: 
1.203     brouard  5295:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5296: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5297: /* { */
                   5298: /*   int i; */
                   5299: /*   int l=1, lmax=20; */
                   5300: /*   double k1,k2,k3,k4,res,fx; */
                   5301: /*   double p2[MAXPARM+1]; */
                   5302: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5303: /*   int k=0,kmax=10; */
                   5304: /*   double l1; */
                   5305:   
                   5306: /*   fx=func(x); */
                   5307: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5308: /*     l1=pow(10,l); */
                   5309: /*     delts=delt; */
                   5310: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5311: /*       delt = delti*(l1*k); */
                   5312: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5313: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5314: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5315: /*       k1=func(p2)-fx; */
                   5316:       
                   5317: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5318: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5319: /*       k2=func(p2)-fx; */
                   5320:       
                   5321: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5322: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5323: /*       k3=func(p2)-fx; */
                   5324:       
                   5325: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5326: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5327: /*       k4=func(p2)-fx; */
                   5328: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5329: /* #ifdef DEBUGHESSIJ */
                   5330: /*       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); */
                   5331: /*       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); */
                   5332: /* #endif */
                   5333: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5334: /*     k=kmax; */
                   5335: /*       } */
                   5336: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5337: /*     k=kmax; l=lmax*10; */
                   5338: /*       } */
                   5339: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5340: /*     delts=delt; */
                   5341: /*       } */
                   5342: /*     } /\* End loop k *\/ */
                   5343: /*   } */
                   5344: /*   delti[theta]=delts; */
                   5345: /*   return res;  */
                   5346: /* } */
                   5347: 
                   5348: 
1.126     brouard  5349: /************** Inverse of matrix **************/
                   5350: void ludcmp(double **a, int n, int *indx, double *d) 
                   5351: { 
                   5352:   int i,imax,j,k; 
                   5353:   double big,dum,sum,temp; 
                   5354:   double *vv; 
                   5355:  
                   5356:   vv=vector(1,n); 
                   5357:   *d=1.0; 
                   5358:   for (i=1;i<=n;i++) { 
                   5359:     big=0.0; 
                   5360:     for (j=1;j<=n;j++) 
                   5361:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5362:     if (big == 0.0){
                   5363:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5364:       for (j=1;j<=n;j++) {
                   5365:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5366:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5367:       }
                   5368:       fflush(ficlog);
                   5369:       fclose(ficlog);
                   5370:       nrerror("Singular matrix in routine ludcmp"); 
                   5371:     }
1.126     brouard  5372:     vv[i]=1.0/big; 
                   5373:   } 
                   5374:   for (j=1;j<=n;j++) { 
                   5375:     for (i=1;i<j;i++) { 
                   5376:       sum=a[i][j]; 
                   5377:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5378:       a[i][j]=sum; 
                   5379:     } 
                   5380:     big=0.0; 
                   5381:     for (i=j;i<=n;i++) { 
                   5382:       sum=a[i][j]; 
                   5383:       for (k=1;k<j;k++) 
                   5384:        sum -= a[i][k]*a[k][j]; 
                   5385:       a[i][j]=sum; 
                   5386:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5387:        big=dum; 
                   5388:        imax=i; 
                   5389:       } 
                   5390:     } 
                   5391:     if (j != imax) { 
                   5392:       for (k=1;k<=n;k++) { 
                   5393:        dum=a[imax][k]; 
                   5394:        a[imax][k]=a[j][k]; 
                   5395:        a[j][k]=dum; 
                   5396:       } 
                   5397:       *d = -(*d); 
                   5398:       vv[imax]=vv[j]; 
                   5399:     } 
                   5400:     indx[j]=imax; 
                   5401:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5402:     if (j != n) { 
                   5403:       dum=1.0/(a[j][j]); 
                   5404:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5405:     } 
                   5406:   } 
                   5407:   free_vector(vv,1,n);  /* Doesn't work */
                   5408: ;
                   5409: } 
                   5410: 
                   5411: void lubksb(double **a, int n, int *indx, double b[]) 
                   5412: { 
                   5413:   int i,ii=0,ip,j; 
                   5414:   double sum; 
                   5415:  
                   5416:   for (i=1;i<=n;i++) { 
                   5417:     ip=indx[i]; 
                   5418:     sum=b[ip]; 
                   5419:     b[ip]=b[i]; 
                   5420:     if (ii) 
                   5421:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5422:     else if (sum) ii=i; 
                   5423:     b[i]=sum; 
                   5424:   } 
                   5425:   for (i=n;i>=1;i--) { 
                   5426:     sum=b[i]; 
                   5427:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5428:     b[i]=sum/a[i][i]; 
                   5429:   } 
                   5430: } 
                   5431: 
                   5432: void pstamp(FILE *fichier)
                   5433: {
1.196     brouard  5434:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5435: }
                   5436: 
1.297     brouard  5437: void date2dmy(double date,double *day, double *month, double *year){
                   5438:   double yp=0., yp1=0., yp2=0.;
                   5439:   
                   5440:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5441:                        fractional in yp1 */
                   5442:   *year=yp;
                   5443:   yp2=modf((yp1*12),&yp);
                   5444:   *month=yp;
                   5445:   yp1=modf((yp2*30.5),&yp);
                   5446:   *day=yp;
                   5447:   if(*day==0) *day=1;
                   5448:   if(*month==0) *month=1;
                   5449: }
                   5450: 
1.253     brouard  5451: 
                   5452: 
1.126     brouard  5453: /************ Frequencies ********************/
1.251     brouard  5454: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5455:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5456:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5457: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5458:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5459:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5460:   int iind=0, iage=0;
                   5461:   int mi; /* Effective wave */
                   5462:   int first;
                   5463:   double ***freq; /* Frequencies */
1.268     brouard  5464:   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 */
                   5465:   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  5466:   double *meanq, *stdq, *idq;
1.226     brouard  5467:   double **meanqt;
                   5468:   double *pp, **prop, *posprop, *pospropt;
                   5469:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5470:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5471:   double agebegin, ageend;
                   5472:     
                   5473:   pp=vector(1,nlstate);
1.251     brouard  5474:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5475:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5476:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5477:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5478:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5479:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5480:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5481:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5482:   strcpy(fileresp,"P_");
                   5483:   strcat(fileresp,fileresu);
                   5484:   /*strcat(fileresphtm,fileresu);*/
                   5485:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5486:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5487:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5488:     exit(0);
                   5489:   }
1.240     brouard  5490:   
1.226     brouard  5491:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5492:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5493:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5494:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5495:     fflush(ficlog);
                   5496:     exit(70); 
                   5497:   }
                   5498:   else{
                   5499:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5500: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5501: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5502:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5503:   }
1.319     brouard  5504:   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  5505:   
1.226     brouard  5506:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5507:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5508:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5509:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5510:     fflush(ficlog);
                   5511:     exit(70); 
1.240     brouard  5512:   } else{
1.226     brouard  5513:     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  5514: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5515: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5516:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5517:   }
1.319     brouard  5518:   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  5519:   
1.253     brouard  5520:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5521:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5522:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5523:   j1=0;
1.126     brouard  5524:   
1.227     brouard  5525:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5526:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5527:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5528:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5529:   
                   5530:   
1.226     brouard  5531:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5532:      reference=low_education V1=0,V2=0
                   5533:      med_educ                V1=1 V2=0, 
                   5534:      high_educ               V1=0 V2=1
1.330     brouard  5535:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5536:   */
1.249     brouard  5537:   dateintsum=0;
                   5538:   k2cpt=0;
                   5539: 
1.253     brouard  5540:   if(cptcoveff == 0 )
1.265     brouard  5541:     nl=1;  /* Constant and age model only */
1.253     brouard  5542:   else
                   5543:     nl=2;
1.265     brouard  5544: 
                   5545:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5546:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5547:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5548:    *     freq[s1][s2][iage] =0.
                   5549:    *     Loop on iind
                   5550:    *       ++freq[s1][s2][iage] weighted
                   5551:    *     end iind
                   5552:    *     if covariate and j!0
                   5553:    *       headers Variable on one line
                   5554:    *     endif cov j!=0
                   5555:    *     header of frequency table by age
                   5556:    *     Loop on age
                   5557:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5558:    *       pos+=freq[s1][s2][iage] weighted
                   5559:    *       Loop on s1 initial state
                   5560:    *         fprintf(ficresp
                   5561:    *       end s1
                   5562:    *     end age
                   5563:    *     if j!=0 computes starting values
                   5564:    *     end compute starting values
                   5565:    *   end j1
                   5566:    * end nl 
                   5567:    */
1.253     brouard  5568:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5569:     if(nj==1)
                   5570:       j=0;  /* First pass for the constant */
1.265     brouard  5571:     else{
1.335     brouard  5572:       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  5573:     }
1.251     brouard  5574:     first=1;
1.332     brouard  5575:     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  5576:       posproptt=0.;
1.330     brouard  5577:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5578:        scanf("%d", i);*/
                   5579:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5580:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5581:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5582:            freq[i][s2][m]=0;
1.251     brouard  5583:       
                   5584:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5585:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5586:          prop[i][m]=0;
                   5587:        posprop[i]=0;
                   5588:        pospropt[i]=0;
                   5589:       }
1.283     brouard  5590:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5591:         idq[z1]=0.;
                   5592:         meanq[z1]=0.;
                   5593:         stdq[z1]=0.;
1.283     brouard  5594:       }
                   5595:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5596:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5597:       /*         meanqt[m][z1]=0.; */
                   5598:       /*       } */
                   5599:       /* }       */
1.251     brouard  5600:       /* dateintsum=0; */
                   5601:       /* k2cpt=0; */
                   5602:       
1.265     brouard  5603:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5604:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5605:        bool=1;
                   5606:        if(j !=0){
                   5607:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5608:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5609:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5610:                /* if(Tvaraff[z1] ==-20){ */
                   5611:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5612:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5613:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5614:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5615:                /* 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); */
                   5616:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5617:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5618:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5619:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5620:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5621:                  /* 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", */
                   5622:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5623:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5624:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5625:                } /* Onlyf fixed */
                   5626:              } /* end z1 */
1.335     brouard  5627:            } /* cptcoveff > 0 */
1.251     brouard  5628:          } /* end any */
                   5629:        }/* end j==0 */
1.265     brouard  5630:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5631:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5632:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5633:            m=mw[mi][iind];
                   5634:            if(j!=0){
                   5635:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5636:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5637:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5638:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5639:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5640:                    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  5641:                                                                                      value is -1, we don't select. It differs from the 
                   5642:                                                                                      constant and age model which counts them. */
                   5643:                      bool=0; /* not selected */
                   5644:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5645:                    /* i1=Tvaraff[z1]; */
                   5646:                    /* i2=TnsdVar[i1]; */
                   5647:                    /* i3=nbcode[i1][i2]; */
                   5648:                    /* i4=covar[i1][iind]; */
                   5649:                    /* if(i4 != i3){ */
                   5650:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5651:                      bool=0;
                   5652:                    }
                   5653:                  }
                   5654:                }
                   5655:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5656:            } /* end j==0 */
                   5657:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5658:            if(bool==1){ /*Selected */
1.251     brouard  5659:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5660:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5661:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5662:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5663:              if(m >=firstpass && m <=lastpass){
                   5664:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5665:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5666:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5667:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5668:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5669:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5670:                if (m<lastpass) {
                   5671:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5672:                  /*   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]); */
                   5673:                  if(s[m][iind]==-1)
                   5674:                    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.));
                   5675:                  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  5676:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5677:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5678:                      idq[z1]=idq[z1]+weight[iind];
                   5679:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5680:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5681:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5682:                    }
1.284     brouard  5683:                  }
1.251     brouard  5684:                  /* if((int)agev[m][iind] == 55) */
                   5685:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5686:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5687:                  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  5688:                }
1.251     brouard  5689:              } /* end if between passes */  
                   5690:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5691:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5692:                k2cpt++;
                   5693:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5694:              }
1.251     brouard  5695:            }else{
                   5696:              bool=1;
                   5697:            }/* end bool 2 */
                   5698:          } /* end m */
1.284     brouard  5699:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5700:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5701:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5702:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5703:          /* } */
1.251     brouard  5704:        } /* end bool */
                   5705:       } /* end iind = 1 to imx */
1.319     brouard  5706:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5707:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5708:       
                   5709:       
                   5710:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5711:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5712:         pstamp(ficresp);
1.335     brouard  5713:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5714:         pstamp(ficresp);
1.251     brouard  5715:        printf( "\n#********** Variable "); 
                   5716:        fprintf(ficresp, "\n#********** Variable "); 
                   5717:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5718:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5719:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5720:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5721:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5722:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5723:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5724:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5725:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5726:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5727:          }else{
1.330     brouard  5728:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5729:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5730:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5731:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5732:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5733:          }
                   5734:        }
                   5735:        printf( "**********\n#");
                   5736:        fprintf(ficresp, "**********\n#");
                   5737:        fprintf(ficresphtm, "**********</h3>\n");
                   5738:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5739:        fprintf(ficlog, "**********\n");
                   5740:       }
1.284     brouard  5741:       /*
                   5742:        Printing means of quantitative variables if any
                   5743:       */
                   5744:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5745:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5746:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5747:        if(weightopt==1){
                   5748:          printf(" Weighted mean and standard deviation of");
                   5749:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5750:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5751:        }
1.311     brouard  5752:        /* mu = \frac{w x}{\sum w}
                   5753:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5754:        */
                   5755:        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]));
                   5756:        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]));
                   5757:        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  5758:       }
                   5759:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5760:       /*       for(m=1;m<=lastpass;m++){ */
                   5761:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5762:       /*   } */
                   5763:       /* } */
1.283     brouard  5764: 
1.251     brouard  5765:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5766:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5767:         fprintf(ficresp, " Age");
1.335     brouard  5768:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5769:          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]]);
                   5770:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5771:        }
1.251     brouard  5772:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5773:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5774:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5775:       }
1.335     brouard  5776:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5777:       fprintf(ficresphtm, "\n");
                   5778:       
                   5779:       /* Header of frequency table by age */
                   5780:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5781:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5782:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5783:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5784:          if(s2!=0 && m!=0)
                   5785:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5786:        }
1.226     brouard  5787:       }
1.251     brouard  5788:       fprintf(ficresphtmfr, "\n");
                   5789:     
                   5790:       /* For each age */
                   5791:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5792:        fprintf(ficresphtm,"<tr>");
                   5793:        if(iage==iagemax+1){
                   5794:          fprintf(ficlog,"1");
                   5795:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5796:        }else if(iage==iagemax+2){
                   5797:          fprintf(ficlog,"0");
                   5798:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5799:        }else if(iage==iagemax+3){
                   5800:          fprintf(ficlog,"Total");
                   5801:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5802:        }else{
1.240     brouard  5803:          if(first==1){
1.251     brouard  5804:            first=0;
                   5805:            printf("See log file for details...\n");
                   5806:          }
                   5807:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5808:          fprintf(ficlog,"Age %d", iage);
                   5809:        }
1.265     brouard  5810:        for(s1=1; s1 <=nlstate ; s1++){
                   5811:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5812:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5813:        }
1.265     brouard  5814:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5815:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5816:            pos += freq[s1][m][iage];
                   5817:          if(pp[s1]>=1.e-10){
1.251     brouard  5818:            if(first==1){
1.265     brouard  5819:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5820:            }
1.265     brouard  5821:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5822:          }else{
                   5823:            if(first==1)
1.265     brouard  5824:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5825:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5826:          }
                   5827:        }
                   5828:       
1.265     brouard  5829:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5830:          /* posprop[s1]=0; */
                   5831:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5832:            pp[s1] += freq[s1][m][iage];
                   5833:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5834:       
                   5835:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5836:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5837:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5838:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5839:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5840:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5841:        }
                   5842:        
                   5843:        /* Writing ficresp */
1.335     brouard  5844:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5845:           if( iage <= iagemax){
                   5846:            fprintf(ficresp," %d",iage);
                   5847:           }
                   5848:         }else if( nj==2){
                   5849:           if( iage <= iagemax){
                   5850:            fprintf(ficresp," %d",iage);
1.335     brouard  5851:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5852:           }
1.240     brouard  5853:        }
1.265     brouard  5854:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5855:          if(pos>=1.e-5){
1.251     brouard  5856:            if(first==1)
1.265     brouard  5857:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5858:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5859:          }else{
                   5860:            if(first==1)
1.265     brouard  5861:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5862:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5863:          }
                   5864:          if( iage <= iagemax){
                   5865:            if(pos>=1.e-5){
1.335     brouard  5866:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5867:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5868:               }else if( nj==2){
                   5869:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5870:               }
                   5871:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5872:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5873:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5874:            } else{
1.335     brouard  5875:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5876:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5877:            }
1.240     brouard  5878:          }
1.265     brouard  5879:          pospropt[s1] +=posprop[s1];
                   5880:        } /* end loop s1 */
1.251     brouard  5881:        /* pospropt=0.; */
1.265     brouard  5882:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5883:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5884:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5885:              if(first==1){
1.265     brouard  5886:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5887:              }
1.265     brouard  5888:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5889:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5890:            }
1.265     brouard  5891:            if(s1!=0 && m!=0)
                   5892:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5893:          }
1.265     brouard  5894:        } /* end loop s1 */
1.251     brouard  5895:        posproptt=0.; 
1.265     brouard  5896:        for(s1=1; s1 <=nlstate; s1++){
                   5897:          posproptt += pospropt[s1];
1.251     brouard  5898:        }
                   5899:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5900:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5901:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5902:          if(iage <= iagemax)
                   5903:            fprintf(ficresp,"\n");
1.240     brouard  5904:        }
1.251     brouard  5905:        if(first==1)
                   5906:          printf("Others in log...\n");
                   5907:        fprintf(ficlog,"\n");
                   5908:       } /* end loop age iage */
1.265     brouard  5909:       
1.251     brouard  5910:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5911:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5912:        if(posproptt < 1.e-5){
1.265     brouard  5913:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5914:        }else{
1.265     brouard  5915:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5916:        }
1.226     brouard  5917:       }
1.251     brouard  5918:       fprintf(ficresphtm,"</tr>\n");
                   5919:       fprintf(ficresphtm,"</table>\n");
                   5920:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5921:       if(posproptt < 1.e-5){
1.251     brouard  5922:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5923:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5924:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5925:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5926:        invalidvarcomb[j1]=1;
1.226     brouard  5927:       }else{
1.338     brouard  5928:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5929:        invalidvarcomb[j1]=0;
1.226     brouard  5930:       }
1.251     brouard  5931:       fprintf(ficresphtmfr,"</table>\n");
                   5932:       fprintf(ficlog,"\n");
                   5933:       if(j!=0){
                   5934:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5935:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5936:          for(k=1; k <=(nlstate+ndeath); k++){
                   5937:            if (k != i) {
1.265     brouard  5938:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5939:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5940:                  if(j1==1){ /* All dummy covariates to zero */
                   5941:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5942:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5943:                    printf("%d%d ",i,k);
                   5944:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5945:                    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]));
                   5946:                    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]));
                   5947:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5948:                  }
1.253     brouard  5949:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5950:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5951:                    x[iage]= (double)iage;
                   5952:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5953:                    /* 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  5954:                  }
1.268     brouard  5955:                  /* Some are not finite, but linreg will ignore these ages */
                   5956:                  no=0;
1.253     brouard  5957:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5958:                  pstart[s1]=b;
                   5959:                  pstart[s1-1]=a;
1.252     brouard  5960:                }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 */ 
                   5961:                  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]);
                   5962:                  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  5963:                  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  5964:                  printf("%d%d ",i,k);
                   5965:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5966:                  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  5967:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5968:                  ;
                   5969:                }
                   5970:                /* printf("%12.7f )", param[i][jj][k]); */
                   5971:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5972:                s1++; 
1.251     brouard  5973:              } /* end jj */
                   5974:            } /* end k!= i */
                   5975:          } /* end k */
1.265     brouard  5976:        } /* end i, s1 */
1.251     brouard  5977:       } /* end j !=0 */
                   5978:     } /* end selected combination of covariate j1 */
                   5979:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5980:       printf("#Freqsummary: Starting values for the constants:\n");
                   5981:       fprintf(ficlog,"\n");
1.265     brouard  5982:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5983:        for(k=1; k <=(nlstate+ndeath); k++){
                   5984:          if (k != i) {
                   5985:            printf("%d%d ",i,k);
                   5986:            fprintf(ficlog,"%d%d ",i,k);
                   5987:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5988:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5989:              if(jj==1){ /* Age has to be done */
1.265     brouard  5990:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5991:                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]));
                   5992:                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  5993:              }
                   5994:              /* printf("%12.7f )", param[i][jj][k]); */
                   5995:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5996:              s1++; 
1.250     brouard  5997:            }
1.251     brouard  5998:            printf("\n");
                   5999:            fprintf(ficlog,"\n");
1.250     brouard  6000:          }
                   6001:        }
1.284     brouard  6002:       } /* end of state i */
1.251     brouard  6003:       printf("#Freqsummary\n");
                   6004:       fprintf(ficlog,"\n");
1.265     brouard  6005:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6006:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6007:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6008:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6009:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6010:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6011:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6012:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  6013:          /* } */
                   6014:        }
1.265     brouard  6015:       } /* end loop s1 */
1.251     brouard  6016:       
                   6017:       printf("\n");
                   6018:       fprintf(ficlog,"\n");
                   6019:     } /* end j=0 */
1.249     brouard  6020:   } /* end j */
1.252     brouard  6021: 
1.253     brouard  6022:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  6023:     for(i=1, jk=1; i <=nlstate; i++){
                   6024:       for(j=1; j <=nlstate+ndeath; j++){
                   6025:        if(j!=i){
                   6026:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6027:          printf("%1d%1d",i,j);
                   6028:          fprintf(ficparo,"%1d%1d",i,j);
                   6029:          for(k=1; k<=ncovmodel;k++){
                   6030:            /*    printf(" %lf",param[i][j][k]); */
                   6031:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6032:            p[jk]=pstart[jk];
                   6033:            printf(" %f ",pstart[jk]);
                   6034:            fprintf(ficparo," %f ",pstart[jk]);
                   6035:            jk++;
                   6036:          }
                   6037:          printf("\n");
                   6038:          fprintf(ficparo,"\n");
                   6039:        }
                   6040:       }
                   6041:     }
                   6042:   } /* end mle=-2 */
1.226     brouard  6043:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  6044:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  6045:   
1.226     brouard  6046:   fclose(ficresp);
                   6047:   fclose(ficresphtm);
                   6048:   fclose(ficresphtmfr);
1.283     brouard  6049:   free_vector(idq,1,nqfveff);
1.226     brouard  6050:   free_vector(meanq,1,nqfveff);
1.284     brouard  6051:   free_vector(stdq,1,nqfveff);
1.226     brouard  6052:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  6053:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6054:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  6055:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6056:   free_vector(pospropt,1,nlstate);
                   6057:   free_vector(posprop,1,nlstate);
1.251     brouard  6058:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  6059:   free_vector(pp,1,nlstate);
                   6060:   /* End of freqsummary */
                   6061: }
1.126     brouard  6062: 
1.268     brouard  6063: /* Simple linear regression */
                   6064: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6065: 
                   6066:   /* y=a+bx regression */
                   6067:   double   sumx = 0.0;                        /* sum of x                      */
                   6068:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6069:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6070:   double   sumy = 0.0;                        /* sum of y                      */
                   6071:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6072:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6073:   double yhat;
                   6074:   
                   6075:   double denom=0;
                   6076:   int i;
                   6077:   int ne=*no;
                   6078:   
                   6079:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6080:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6081:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6082:       continue;
                   6083:     }
                   6084:     ne=ne+1;
                   6085:     sumx  += x[i];       
                   6086:     sumx2 += x[i]*x[i];  
                   6087:     sumxy += x[i] * y[i];
                   6088:     sumy  += y[i];      
                   6089:     sumy2 += y[i]*y[i]; 
                   6090:     denom = (ne * sumx2 - sumx*sumx);
                   6091:     /* 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); */
                   6092:   } 
                   6093:   
                   6094:   denom = (ne * sumx2 - sumx*sumx);
                   6095:   if (denom == 0) {
                   6096:     // vertical, slope m is infinity
                   6097:     *b = INFINITY;
                   6098:     *a = 0;
                   6099:     if (r) *r = 0;
                   6100:     return 1;
                   6101:   }
                   6102:   
                   6103:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6104:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6105:   if (r!=NULL) {
                   6106:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6107:       sqrt((sumx2 - sumx*sumx/ne) *
                   6108:           (sumy2 - sumy*sumy/ne));
                   6109:   }
                   6110:   *no=ne;
                   6111:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6112:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6113:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6114:       continue;
                   6115:     }
                   6116:     ne=ne+1;
                   6117:     yhat = y[i] - *a -*b* x[i];
                   6118:     sume2  += yhat * yhat ;       
                   6119:     
                   6120:     denom = (ne * sumx2 - sumx*sumx);
                   6121:     /* 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); */
                   6122:   } 
                   6123:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6124:   *sa= *sb * sqrt(sumx2/ne);
                   6125:   
                   6126:   return 0; 
                   6127: }
                   6128: 
1.126     brouard  6129: /************ Prevalence ********************/
1.227     brouard  6130: 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)
                   6131: {  
                   6132:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6133:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6134:      We still use firstpass and lastpass as another selection.
                   6135:   */
1.126     brouard  6136:  
1.227     brouard  6137:   int i, m, jk, j1, bool, z1,j, iv;
                   6138:   int mi; /* Effective wave */
                   6139:   int iage;
                   6140:   double agebegin, ageend;
                   6141: 
                   6142:   double **prop;
                   6143:   double posprop; 
                   6144:   double  y2; /* in fractional years */
                   6145:   int iagemin, iagemax;
                   6146:   int first; /** to stop verbosity which is redirected to log file */
                   6147: 
                   6148:   iagemin= (int) agemin;
                   6149:   iagemax= (int) agemax;
                   6150:   /*pp=vector(1,nlstate);*/
1.251     brouard  6151:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  6152:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6153:   j1=0;
1.222     brouard  6154:   
1.227     brouard  6155:   /*j=cptcoveff;*/
                   6156:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  6157:   
1.288     brouard  6158:   first=0;
1.335     brouard  6159:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  6160:     for (i=1; i<=nlstate; i++)  
1.251     brouard  6161:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  6162:        prop[i][iage]=0.0;
                   6163:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6164:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6165:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6166:     
                   6167:     for (i=1; i<=imx; i++) { /* Each individual */
                   6168:       bool=1;
                   6169:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6170:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6171:        m=mw[mi][i];
                   6172:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6173:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6174:        for (z1=1; z1<=cptcoveff; z1++){
                   6175:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  6176:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  6177:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  6178:              bool=0;
                   6179:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  6180:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  6181:              bool=0;
                   6182:            }
                   6183:        }
                   6184:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6185:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6186:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6187:          if(m >=firstpass && m <=lastpass){
                   6188:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6189:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6190:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6191:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  6192:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  6193:                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); 
                   6194:                exit(1);
                   6195:              }
                   6196:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6197:                /*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]]);*/
                   6198:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6199:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6200:              } /* end valid statuses */ 
                   6201:            } /* end selection of dates */
                   6202:          } /* end selection of waves */
                   6203:        } /* end bool */
                   6204:       } /* end wave */
                   6205:     } /* end individual */
                   6206:     for(i=iagemin; i <= iagemax+3; i++){  
                   6207:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6208:        posprop += prop[jk][i]; 
                   6209:       } 
                   6210:       
                   6211:       for(jk=1; jk <=nlstate ; jk++){      
                   6212:        if( i <=  iagemax){ 
                   6213:          if(posprop>=1.e-5){ 
                   6214:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6215:          } else{
1.288     brouard  6216:            if(!first){
                   6217:              first=1;
1.266     brouard  6218:              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]);
                   6219:            }else{
1.288     brouard  6220:              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  6221:            }
                   6222:          }
                   6223:        } 
                   6224:       }/* end jk */ 
                   6225:     }/* end i */ 
1.222     brouard  6226:      /*} *//* end i1 */
1.227     brouard  6227:   } /* end j1 */
1.222     brouard  6228:   
1.227     brouard  6229:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6230:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  6231:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  6232: }  /* End of prevalence */
1.126     brouard  6233: 
                   6234: /************* Waves Concatenation ***************/
                   6235: 
                   6236: 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)
                   6237: {
1.298     brouard  6238:   /* 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  6239:      Death is a valid wave (if date is known).
                   6240:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6241:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6242:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6243:   */
1.126     brouard  6244: 
1.224     brouard  6245:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6246:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6247:      double sum=0., jmean=0.;*/
1.224     brouard  6248:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6249:   int j, k=0,jk, ju, jl;
                   6250:   double sum=0.;
                   6251:   first=0;
1.214     brouard  6252:   firstwo=0;
1.217     brouard  6253:   firsthree=0;
1.218     brouard  6254:   firstfour=0;
1.164     brouard  6255:   jmin=100000;
1.126     brouard  6256:   jmax=-1;
                   6257:   jmean=0.;
1.224     brouard  6258: 
                   6259: /* Treating live states */
1.214     brouard  6260:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6261:     mi=0;  /* First valid wave */
1.227     brouard  6262:     mli=0; /* Last valid wave */
1.309     brouard  6263:     m=firstpass;  /* Loop on waves */
                   6264:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6265:       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 */
                   6266:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6267:       }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  6268:        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  6269:        mli=m;
1.224     brouard  6270:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6271:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6272:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6273:       }
1.309     brouard  6274:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6275: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6276:        break;
1.224     brouard  6277: #else
1.317     brouard  6278:        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  6279:          if(firsthree == 0){
1.302     brouard  6280:            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  6281:            firsthree=1;
1.317     brouard  6282:          }else if(firsthree >=1 && firsthree < 10){
                   6283:            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);
                   6284:            firsthree++;
                   6285:          }else if(firsthree == 10){
                   6286:            printf("Information, too many Information flags: no more reported to log either\n");
                   6287:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6288:            firsthree++;
                   6289:          }else{
                   6290:            firsthree++;
1.227     brouard  6291:          }
1.309     brouard  6292:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6293:          mli=m;
                   6294:        }
                   6295:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6296:          nbwarn++;
1.309     brouard  6297:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6298:            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);
                   6299:            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);
                   6300:          }
                   6301:          break;
                   6302:        }
                   6303:        break;
1.224     brouard  6304: #endif
1.227     brouard  6305:       }/* End m >= lastpass */
1.126     brouard  6306:     }/* end while */
1.224     brouard  6307: 
1.227     brouard  6308:     /* 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  6309:     /* After last pass */
1.224     brouard  6310: /* Treating death states */
1.214     brouard  6311:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6312:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6313:       /* } */
1.126     brouard  6314:       mi++;    /* Death is another wave */
                   6315:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6316:       /* Only death is a correct wave */
1.126     brouard  6317:       mw[mi][i]=m;
1.257     brouard  6318:     } /* else not in a death state */
1.224     brouard  6319: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6320:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6321:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6322:        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  6323:          nbwarn++;
                   6324:          if(firstfiv==0){
1.309     brouard  6325:            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  6326:            firstfiv=1;
                   6327:          }else{
1.309     brouard  6328:            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  6329:          }
1.309     brouard  6330:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6331:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6332:          nberr++;
                   6333:          if(firstwo==0){
1.309     brouard  6334:            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  6335:            firstwo=1;
                   6336:          }
1.309     brouard  6337:          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  6338:        }
1.257     brouard  6339:       }else{ /* if date of interview is unknown */
1.227     brouard  6340:        /* death is known but not confirmed by death status at any wave */
                   6341:        if(firstfour==0){
1.309     brouard  6342:          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  6343:          firstfour=1;
                   6344:        }
1.309     brouard  6345:        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  6346:       }
1.224     brouard  6347:     } /* end if date of death is known */
                   6348: #endif
1.309     brouard  6349:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6350:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6351:     if(mi==0){
                   6352:       nbwarn++;
                   6353:       if(first==0){
1.227     brouard  6354:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6355:        first=1;
1.126     brouard  6356:       }
                   6357:       if(first==1){
1.227     brouard  6358:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6359:       }
                   6360:     } /* end mi==0 */
                   6361:   } /* End individuals */
1.214     brouard  6362:   /* wav and mw are no more changed */
1.223     brouard  6363:        
1.317     brouard  6364:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6365:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6366: 
                   6367: 
1.126     brouard  6368:   for(i=1; i<=imx; i++){
                   6369:     for(mi=1; mi<wav[i];mi++){
                   6370:       if (stepm <=0)
1.227     brouard  6371:        dh[mi][i]=1;
1.126     brouard  6372:       else{
1.260     brouard  6373:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6374:          if (agedc[i] < 2*AGESUP) {
                   6375:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6376:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6377:            else if(j<0){
                   6378:              nberr++;
                   6379:              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]);
                   6380:              j=1; /* Temporary Dangerous patch */
                   6381:              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);
                   6382:              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]);
                   6383:              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);
                   6384:            }
                   6385:            k=k+1;
                   6386:            if (j >= jmax){
                   6387:              jmax=j;
                   6388:              ijmax=i;
                   6389:            }
                   6390:            if (j <= jmin){
                   6391:              jmin=j;
                   6392:              ijmin=i;
                   6393:            }
                   6394:            sum=sum+j;
                   6395:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6396:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6397:          }
                   6398:        }
                   6399:        else{
                   6400:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6401: /*       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  6402:                                        
1.227     brouard  6403:          k=k+1;
                   6404:          if (j >= jmax) {
                   6405:            jmax=j;
                   6406:            ijmax=i;
                   6407:          }
                   6408:          else if (j <= jmin){
                   6409:            jmin=j;
                   6410:            ijmin=i;
                   6411:          }
                   6412:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6413:          /*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]);*/
                   6414:          if(j<0){
                   6415:            nberr++;
                   6416:            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]);
                   6417:            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]);
                   6418:          }
                   6419:          sum=sum+j;
                   6420:        }
                   6421:        jk= j/stepm;
                   6422:        jl= j -jk*stepm;
                   6423:        ju= j -(jk+1)*stepm;
                   6424:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6425:          if(jl==0){
                   6426:            dh[mi][i]=jk;
                   6427:            bh[mi][i]=0;
                   6428:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6429:                  * to avoid the price of an extra matrix product in likelihood */
                   6430:            dh[mi][i]=jk+1;
                   6431:            bh[mi][i]=ju;
                   6432:          }
                   6433:        }else{
                   6434:          if(jl <= -ju){
                   6435:            dh[mi][i]=jk;
                   6436:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6437:                                 * is higher than the multiple of stepm and negative otherwise.
                   6438:                                 */
                   6439:          }
                   6440:          else{
                   6441:            dh[mi][i]=jk+1;
                   6442:            bh[mi][i]=ju;
                   6443:          }
                   6444:          if(dh[mi][i]==0){
                   6445:            dh[mi][i]=1; /* At least one step */
                   6446:            bh[mi][i]=ju; /* At least one step */
                   6447:            /*  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);*/
                   6448:          }
                   6449:        } /* end if mle */
1.126     brouard  6450:       }
                   6451:     } /* end wave */
                   6452:   }
                   6453:   jmean=sum/k;
                   6454:   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  6455:   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  6456: }
1.126     brouard  6457: 
                   6458: /*********** Tricode ****************************/
1.220     brouard  6459:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6460:  {
                   6461:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6462:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6463:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6464:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6465:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6466:     */
1.130     brouard  6467: 
1.242     brouard  6468:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6469:    int modmaxcovj=0; /* Modality max of covariates j */
                   6470:    int cptcode=0; /* Modality max of covariates j */
                   6471:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6472: 
                   6473: 
1.242     brouard  6474:    /* cptcoveff=0;  */
                   6475:    /* *cptcov=0; */
1.126     brouard  6476:  
1.242     brouard  6477:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6478:    for (k=1; k <= maxncov; k++)
                   6479:      for(j=1; j<=2; j++)
                   6480:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6481: 
1.242     brouard  6482:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6483:    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  6484:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  6485:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  6486:      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  6487:        switch(Fixed[k]) {
                   6488:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6489:         modmaxcovj=0;
                   6490:         modmincovj=0;
1.242     brouard  6491:         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  6492:           /* 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  6493:           ij=(int)(covar[Tvar[k]][i]);
                   6494:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6495:            * If product of Vn*Vm, still boolean *:
                   6496:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6497:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6498:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6499:              modality of the nth covariate of individual i. */
                   6500:           if (ij > modmaxcovj)
                   6501:             modmaxcovj=ij; 
                   6502:           else if (ij < modmincovj) 
                   6503:             modmincovj=ij; 
1.287     brouard  6504:           if (ij <0 || ij >1 ){
1.311     brouard  6505:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6506:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6507:             fflush(ficlog);
                   6508:             exit(1);
1.287     brouard  6509:           }
                   6510:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6511:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6512:             exit(1);
                   6513:           }else
                   6514:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6515:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6516:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6517:           /* getting the maximum value of the modality of the covariate
                   6518:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6519:              female ies 1, then modmaxcovj=1.
                   6520:           */
                   6521:         } /* end for loop on individuals i */
                   6522:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6523:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6524:         cptcode=modmaxcovj;
                   6525:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6526:         /*for (i=0; i<=cptcode; i++) {*/
                   6527:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6528:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6529:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6530:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6531:             if( j != -1){
                   6532:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6533:                                  covariate for which somebody answered excluding 
                   6534:                                  undefined. Usually 2: 0 and 1. */
                   6535:             }
                   6536:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6537:                                     covariate for which somebody answered including 
                   6538:                                     undefined. Usually 3: -1, 0 and 1. */
                   6539:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6540:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6541:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6542:                        
1.242     brouard  6543:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6544:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6545:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6546:         /* modmincovj=3; modmaxcovj = 7; */
                   6547:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6548:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6549:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6550:         /* nbcode[Tvar[j]][ij]=k; */
                   6551:         /* nbcode[Tvar[j]][1]=0; */
                   6552:         /* nbcode[Tvar[j]][2]=1; */
                   6553:         /* nbcode[Tvar[j]][3]=2; */
                   6554:         /* To be continued (not working yet). */
                   6555:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6556: 
                   6557:         /* 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*/
                   6558:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6559:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6560:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6561:         /*, could be restored in the future */
                   6562:         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  6563:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6564:             break;
                   6565:           }
                   6566:           ij++;
1.287     brouard  6567:           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  6568:           cptcode = ij; /* New max modality for covar j */
                   6569:         } /* end of loop on modality i=-1 to 1 or more */
                   6570:         break;
                   6571:        case 1: /* Testing on varying covariate, could be simple and
                   6572:                * should look at waves or product of fixed *
                   6573:                * varying. No time to test -1, assuming 0 and 1 only */
                   6574:         ij=0;
                   6575:         for(i=0; i<=1;i++){
                   6576:           nbcode[Tvar[k]][++ij]=i;
                   6577:         }
                   6578:         break;
                   6579:        default:
                   6580:         break;
                   6581:        } /* end switch */
                   6582:      } /* end dummy test */
1.349     brouard  6583:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6584:        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  6585:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6586:           printf("Error k=%d \n",k);
                   6587:           exit(1);
                   6588:         }
1.311     brouard  6589:         if(isnan(covar[Tvar[k]][i])){
                   6590:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6591:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6592:           fflush(ficlog);
                   6593:           exit(1);
                   6594:          }
                   6595:        }
1.335     brouard  6596:      } /* end Quanti */
1.287     brouard  6597:    } /* 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  6598:   
                   6599:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6600:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6601:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6602:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6603:      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 */ 
                   6604:      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 */
                   6605:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6606:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6607:   
                   6608:    ij=0;
                   6609:    /* 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  6610:    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 */
                   6611:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6612:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6613:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6614:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6615:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6616:        /* 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  6617:        /* If product not in single variable we don't print results */
                   6618:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6619:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6620:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6621:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6622:        /* ij            1    2                                            3  */  
                   6623:        /* Tvaraff[ij]=  4    3                                            1  */
                   6624:        /* Tmodelind[ij]=2    3                                            9  */
                   6625:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6626:        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*/
                   6627:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6628:        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 */
                   6629:        if(Fixed[k]!=0)
                   6630:         anyvaryingduminmodel=1;
                   6631:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6632:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6633:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6634:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6635:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6636:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6637:      } 
                   6638:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6639:    /* ij--; */
                   6640:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6641:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6642:                * because they can be excluded from the model and real
                   6643:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6644:    for(j=ij+1; j<= cptcovt; j++){
                   6645:      Tvaraff[j]=0;
                   6646:      Tmodelind[j]=0;
                   6647:    }
                   6648:    for(j=ntveff+1; j<= cptcovt; j++){
                   6649:      TmodelInvind[j]=0;
                   6650:    }
                   6651:    /* To be sorted */
                   6652:    ;
                   6653:  }
1.126     brouard  6654: 
1.145     brouard  6655: 
1.126     brouard  6656: /*********** Health Expectancies ****************/
                   6657: 
1.235     brouard  6658:  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  6659: 
                   6660: {
                   6661:   /* Health expectancies, no variances */
1.329     brouard  6662:   /* cij is the combination in the list of combination of dummy covariates */
                   6663:   /* strstart is a string of time at start of computing */
1.164     brouard  6664:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6665:   int nhstepma, nstepma; /* Decreasing with age */
                   6666:   double age, agelim, hf;
                   6667:   double ***p3mat;
                   6668:   double eip;
                   6669: 
1.238     brouard  6670:   /* pstamp(ficreseij); */
1.126     brouard  6671:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6672:   fprintf(ficreseij,"# Age");
                   6673:   for(i=1; i<=nlstate;i++){
                   6674:     for(j=1; j<=nlstate;j++){
                   6675:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6676:     }
                   6677:     fprintf(ficreseij," e%1d. ",i);
                   6678:   }
                   6679:   fprintf(ficreseij,"\n");
                   6680: 
                   6681:   
                   6682:   if(estepm < stepm){
                   6683:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6684:   }
                   6685:   else  hstepm=estepm;   
                   6686:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6687:    * This is mainly to measure the difference between two models: for example
                   6688:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6689:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6690:    * progression in between and thus overestimating or underestimating according
                   6691:    * to the curvature of the survival function. If, for the same date, we 
                   6692:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6693:    * to compare the new estimate of Life expectancy with the same linear 
                   6694:    * hypothesis. A more precise result, taking into account a more precise
                   6695:    * curvature will be obtained if estepm is as small as stepm. */
                   6696: 
                   6697:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6698:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6699:      nhstepm is the number of hstepm from age to agelim 
                   6700:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6701:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6702:      and note for a fixed period like estepm months */
                   6703:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6704:      survival function given by stepm (the optimization length). Unfortunately it
                   6705:      means that if the survival funtion is printed only each two years of age and if
                   6706:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6707:      results. So we changed our mind and took the option of the best precision.
                   6708:   */
                   6709:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6710: 
                   6711:   agelim=AGESUP;
                   6712:   /* If stepm=6 months */
                   6713:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6714:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6715:     
                   6716: /* nhstepm age range expressed in number of stepm */
                   6717:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6718:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6719:   /* if (stepm >= YEARM) hstepm=1;*/
                   6720:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6721:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6722: 
                   6723:   for (age=bage; age<=fage; age ++){ 
                   6724:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6725:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6726:     /* if (stepm >= YEARM) hstepm=1;*/
                   6727:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6728: 
                   6729:     /* If stepm=6 months */
                   6730:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6731:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6732:     /* 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  6733:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6734:     
                   6735:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6736:     
                   6737:     printf("%d|",(int)age);fflush(stdout);
                   6738:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6739:     
                   6740:     /* Computing expectancies */
                   6741:     for(i=1; i<=nlstate;i++)
                   6742:       for(j=1; j<=nlstate;j++)
                   6743:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6744:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6745:          
                   6746:          /* 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]);*/
                   6747: 
                   6748:        }
                   6749: 
                   6750:     fprintf(ficreseij,"%3.0f",age );
                   6751:     for(i=1; i<=nlstate;i++){
                   6752:       eip=0;
                   6753:       for(j=1; j<=nlstate;j++){
                   6754:        eip +=eij[i][j][(int)age];
                   6755:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6756:       }
                   6757:       fprintf(ficreseij,"%9.4f", eip );
                   6758:     }
                   6759:     fprintf(ficreseij,"\n");
                   6760:     
                   6761:   }
                   6762:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6763:   printf("\n");
                   6764:   fprintf(ficlog,"\n");
                   6765:   
                   6766: }
                   6767: 
1.235     brouard  6768:  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  6769: 
                   6770: {
                   6771:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6772:      to initial status i, ei. .
1.126     brouard  6773:   */
1.336     brouard  6774:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6775:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6776:   int nhstepma, nstepma; /* Decreasing with age */
                   6777:   double age, agelim, hf;
                   6778:   double ***p3matp, ***p3matm, ***varhe;
                   6779:   double **dnewm,**doldm;
                   6780:   double *xp, *xm;
                   6781:   double **gp, **gm;
                   6782:   double ***gradg, ***trgradg;
                   6783:   int theta;
                   6784: 
                   6785:   double eip, vip;
                   6786: 
                   6787:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6788:   xp=vector(1,npar);
                   6789:   xm=vector(1,npar);
                   6790:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6791:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6792:   
                   6793:   pstamp(ficresstdeij);
                   6794:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6795:   fprintf(ficresstdeij,"# Age");
                   6796:   for(i=1; i<=nlstate;i++){
                   6797:     for(j=1; j<=nlstate;j++)
                   6798:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6799:     fprintf(ficresstdeij," e%1d. ",i);
                   6800:   }
                   6801:   fprintf(ficresstdeij,"\n");
                   6802: 
                   6803:   pstamp(ficrescveij);
                   6804:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6805:   fprintf(ficrescveij,"# Age");
                   6806:   for(i=1; i<=nlstate;i++)
                   6807:     for(j=1; j<=nlstate;j++){
                   6808:       cptj= (j-1)*nlstate+i;
                   6809:       for(i2=1; i2<=nlstate;i2++)
                   6810:        for(j2=1; j2<=nlstate;j2++){
                   6811:          cptj2= (j2-1)*nlstate+i2;
                   6812:          if(cptj2 <= cptj)
                   6813:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6814:        }
                   6815:     }
                   6816:   fprintf(ficrescveij,"\n");
                   6817:   
                   6818:   if(estepm < stepm){
                   6819:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6820:   }
                   6821:   else  hstepm=estepm;   
                   6822:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6823:    * This is mainly to measure the difference between two models: for example
                   6824:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6825:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6826:    * progression in between and thus overestimating or underestimating according
                   6827:    * to the curvature of the survival function. If, for the same date, we 
                   6828:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6829:    * to compare the new estimate of Life expectancy with the same linear 
                   6830:    * hypothesis. A more precise result, taking into account a more precise
                   6831:    * curvature will be obtained if estepm is as small as stepm. */
                   6832: 
                   6833:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6834:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6835:      nhstepm is the number of hstepm from age to agelim 
                   6836:      nstepm is the number of stepm from age to agelin. 
                   6837:      Look at hpijx to understand the reason of that which relies in memory size
                   6838:      and note for a fixed period like estepm months */
                   6839:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6840:      survival function given by stepm (the optimization length). Unfortunately it
                   6841:      means that if the survival funtion is printed only each two years of age and if
                   6842:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6843:      results. So we changed our mind and took the option of the best precision.
                   6844:   */
                   6845:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6846: 
                   6847:   /* If stepm=6 months */
                   6848:   /* nhstepm age range expressed in number of stepm */
                   6849:   agelim=AGESUP;
                   6850:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6851:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6852:   /* if (stepm >= YEARM) hstepm=1;*/
                   6853:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6854:   
                   6855:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6856:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6857:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6858:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6859:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6860:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6861: 
                   6862:   for (age=bage; age<=fage; age ++){ 
                   6863:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6864:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6865:     /* if (stepm >= YEARM) hstepm=1;*/
                   6866:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6867:                
1.126     brouard  6868:     /* If stepm=6 months */
                   6869:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6870:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6871:     
                   6872:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6873:                
1.126     brouard  6874:     /* Computing  Variances of health expectancies */
                   6875:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6876:        decrease memory allocation */
                   6877:     for(theta=1; theta <=npar; theta++){
                   6878:       for(i=1; i<=npar; i++){ 
1.222     brouard  6879:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6880:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6881:       }
1.235     brouard  6882:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6883:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6884:                        
1.126     brouard  6885:       for(j=1; j<= nlstate; j++){
1.222     brouard  6886:        for(i=1; i<=nlstate; i++){
                   6887:          for(h=0; h<=nhstepm-1; h++){
                   6888:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6889:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6890:          }
                   6891:        }
1.126     brouard  6892:       }
1.218     brouard  6893:                        
1.126     brouard  6894:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6895:        for(h=0; h<=nhstepm-1; h++){
                   6896:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6897:        }
1.126     brouard  6898:     }/* End theta */
                   6899:     
                   6900:     
                   6901:     for(h=0; h<=nhstepm-1; h++)
                   6902:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6903:        for(theta=1; theta <=npar; theta++)
                   6904:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6905:     
1.218     brouard  6906:                
1.222     brouard  6907:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6908:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6909:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6910:                
1.222     brouard  6911:     printf("%d|",(int)age);fflush(stdout);
                   6912:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6913:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6914:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6915:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6916:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6917:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6918:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6919:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6920:       }
                   6921:     }
1.320     brouard  6922:     /* if((int)age ==50){ */
                   6923:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6924:     /* } */
1.126     brouard  6925:     /* Computing expectancies */
1.235     brouard  6926:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6927:     for(i=1; i<=nlstate;i++)
                   6928:       for(j=1; j<=nlstate;j++)
1.222     brouard  6929:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6930:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6931:                                        
1.222     brouard  6932:          /* 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  6933:                                        
1.222     brouard  6934:        }
1.269     brouard  6935: 
                   6936:     /* Standard deviation of expectancies ij */                
1.126     brouard  6937:     fprintf(ficresstdeij,"%3.0f",age );
                   6938:     for(i=1; i<=nlstate;i++){
                   6939:       eip=0.;
                   6940:       vip=0.;
                   6941:       for(j=1; j<=nlstate;j++){
1.222     brouard  6942:        eip += eij[i][j][(int)age];
                   6943:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6944:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6945:        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  6946:       }
                   6947:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6948:     }
                   6949:     fprintf(ficresstdeij,"\n");
1.218     brouard  6950:                
1.269     brouard  6951:     /* Variance of expectancies ij */          
1.126     brouard  6952:     fprintf(ficrescveij,"%3.0f",age );
                   6953:     for(i=1; i<=nlstate;i++)
                   6954:       for(j=1; j<=nlstate;j++){
1.222     brouard  6955:        cptj= (j-1)*nlstate+i;
                   6956:        for(i2=1; i2<=nlstate;i2++)
                   6957:          for(j2=1; j2<=nlstate;j2++){
                   6958:            cptj2= (j2-1)*nlstate+i2;
                   6959:            if(cptj2 <= cptj)
                   6960:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6961:          }
1.126     brouard  6962:       }
                   6963:     fprintf(ficrescveij,"\n");
1.218     brouard  6964:                
1.126     brouard  6965:   }
                   6966:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6967:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6968:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6969:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6970:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6971:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6972:   printf("\n");
                   6973:   fprintf(ficlog,"\n");
1.218     brouard  6974:        
1.126     brouard  6975:   free_vector(xm,1,npar);
                   6976:   free_vector(xp,1,npar);
                   6977:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6978:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6979:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6980: }
1.218     brouard  6981:  
1.126     brouard  6982: /************ Variance ******************/
1.235     brouard  6983:  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  6984:  {
1.279     brouard  6985:    /** Variance of health expectancies 
                   6986:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6987:     * double **newm;
                   6988:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6989:     */
1.218     brouard  6990:   
                   6991:    /* int movingaverage(); */
                   6992:    double **dnewm,**doldm;
                   6993:    double **dnewmp,**doldmp;
                   6994:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6995:    int first=0;
1.218     brouard  6996:    int k;
                   6997:    double *xp;
1.279     brouard  6998:    double **gp, **gm;  /**< for var eij */
                   6999:    double ***gradg, ***trgradg; /**< for var eij */
                   7000:    double **gradgp, **trgradgp; /**< for var p point j */
                   7001:    double *gpp, *gmp; /**< for var p point j */
                   7002:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  7003:    double ***p3mat;
                   7004:    double age,agelim, hf;
                   7005:    /* double ***mobaverage; */
                   7006:    int theta;
                   7007:    char digit[4];
                   7008:    char digitp[25];
                   7009: 
                   7010:    char fileresprobmorprev[FILENAMELENGTH];
                   7011: 
                   7012:    if(popbased==1){
                   7013:      if(mobilav!=0)
                   7014:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7015:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7016:    }
                   7017:    else 
                   7018:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  7019: 
1.218     brouard  7020:    /* if (mobilav!=0) { */
                   7021:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7022:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7023:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7024:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7025:    /*   } */
                   7026:    /* } */
                   7027: 
                   7028:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7029:    sprintf(digit,"%-d",ij);
                   7030:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7031:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7032:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7033:    strcat(fileresprobmorprev,fileresu);
                   7034:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7035:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7036:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7037:    }
                   7038:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7039:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7040:    pstamp(ficresprobmorprev);
                   7041:    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  7042:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  7043: 
                   7044:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7045:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7046:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7047:    /* } */
                   7048:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  7049:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  7050:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  7051:    }
1.337     brouard  7052:    /* for(j=1;j<=cptcoveff;j++)  */
                   7053:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  7054:    fprintf(ficresprobmorprev,"\n");
                   7055: 
1.218     brouard  7056:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7057:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7058:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7059:      for(i=1; i<=nlstate;i++)
                   7060:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7061:    }  
                   7062:    fprintf(ficresprobmorprev,"\n");
                   7063:   
                   7064:    fprintf(ficgp,"\n# Routine varevsij");
                   7065:    fprintf(ficgp,"\nunset title \n");
                   7066:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7067:    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");
                   7068:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  7069: 
1.218     brouard  7070:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7071:    pstamp(ficresvij);
                   7072:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7073:    if(popbased==1)
                   7074:      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);
                   7075:    else
                   7076:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7077:    fprintf(ficresvij,"# Age");
                   7078:    for(i=1; i<=nlstate;i++)
                   7079:      for(j=1; j<=nlstate;j++)
                   7080:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7081:    fprintf(ficresvij,"\n");
                   7082: 
                   7083:    xp=vector(1,npar);
                   7084:    dnewm=matrix(1,nlstate,1,npar);
                   7085:    doldm=matrix(1,nlstate,1,nlstate);
                   7086:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7087:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7088: 
                   7089:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7090:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7091:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7092:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  7093:   
1.218     brouard  7094:    if(estepm < stepm){
                   7095:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7096:    }
                   7097:    else  hstepm=estepm;   
                   7098:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7099:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7100:       nhstepm is the number of hstepm from age to agelim 
                   7101:       nstepm is the number of stepm from age to agelim. 
                   7102:       Look at function hpijx to understand why because of memory size limitations, 
                   7103:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7104:       survival function given by stepm (the optimization length). Unfortunately it
                   7105:       means that if the survival funtion is printed every two years of age and if
                   7106:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7107:       results. So we changed our mind and took the option of the best precision.
                   7108:    */
                   7109:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7110:    agelim = AGESUP;
                   7111:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7112:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7113:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7114:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7115:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7116:      gp=matrix(0,nhstepm,1,nlstate);
                   7117:      gm=matrix(0,nhstepm,1,nlstate);
                   7118:                
                   7119:                
                   7120:      for(theta=1; theta <=npar; theta++){
                   7121:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7122:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7123:        }
1.279     brouard  7124:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7125:        * returns into prlim .
1.288     brouard  7126:        */
1.242     brouard  7127:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  7128: 
                   7129:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  7130:        if (popbased==1) {
                   7131:         if(mobilav ==0){
                   7132:           for(i=1; i<=nlstate;i++)
                   7133:             prlim[i][i]=probs[(int)age][i][ij];
                   7134:         }else{ /* mobilav */ 
                   7135:           for(i=1; i<=nlstate;i++)
                   7136:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7137:         }
                   7138:        }
1.295     brouard  7139:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  7140:        */                      
                   7141:        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  7142:        /**< 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  7143:        * at horizon h in state j including mortality.
                   7144:        */
1.218     brouard  7145:        for(j=1; j<= nlstate; j++){
                   7146:         for(h=0; h<=nhstepm; h++){
                   7147:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7148:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7149:         }
                   7150:        }
1.279     brouard  7151:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  7152:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  7153:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  7154:        */
                   7155:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7156:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7157:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  7158:        }
                   7159:        
                   7160:        /* Again with minus shift */
1.218     brouard  7161:                        
                   7162:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7163:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7164: 
1.242     brouard  7165:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  7166:                        
                   7167:        if (popbased==1) {
                   7168:         if(mobilav ==0){
                   7169:           for(i=1; i<=nlstate;i++)
                   7170:             prlim[i][i]=probs[(int)age][i][ij];
                   7171:         }else{ /* mobilav */ 
                   7172:           for(i=1; i<=nlstate;i++)
                   7173:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7174:         }
                   7175:        }
                   7176:                        
1.235     brouard  7177:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  7178:                        
                   7179:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7180:         for(h=0; h<=nhstepm; h++){
                   7181:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7182:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7183:         }
                   7184:        }
                   7185:        /* This for computing probability of death (h=1 means
                   7186:          computed over hstepm matrices product = hstepm*stepm months) 
                   7187:          as a weighted average of prlim.
                   7188:        */
                   7189:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7190:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7191:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7192:        }    
1.279     brouard  7193:        /* end shifting computations */
                   7194: 
                   7195:        /**< Computing gradient matrix at horizon h 
                   7196:        */
1.218     brouard  7197:        for(j=1; j<= nlstate; j++) /* vareij */
                   7198:         for(h=0; h<=nhstepm; h++){
                   7199:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7200:         }
1.279     brouard  7201:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7202:        */
                   7203:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  7204:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7205:        }
                   7206:                        
                   7207:      } /* End theta */
1.279     brouard  7208:      
                   7209:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  7210:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7211:                
                   7212:      for(h=0; h<=nhstepm; h++) /* veij */
                   7213:        for(j=1; j<=nlstate;j++)
                   7214:         for(theta=1; theta <=npar; theta++)
                   7215:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7216:                
                   7217:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7218:        for(theta=1; theta <=npar; theta++)
                   7219:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  7220:      /**< as well as its transposed matrix 
                   7221:       */               
1.218     brouard  7222:                
                   7223:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7224:      for(i=1;i<=nlstate;i++)
                   7225:        for(j=1;j<=nlstate;j++)
                   7226:         vareij[i][j][(int)age] =0.;
1.279     brouard  7227: 
                   7228:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7229:       * and k (nhstepm) formula 15 of article
                   7230:       * Lievre-Brouard-Heathcote
                   7231:       */
                   7232:      
1.218     brouard  7233:      for(h=0;h<=nhstepm;h++){
                   7234:        for(k=0;k<=nhstepm;k++){
                   7235:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7236:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7237:         for(i=1;i<=nlstate;i++)
                   7238:           for(j=1;j<=nlstate;j++)
                   7239:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7240:        }
                   7241:      }
                   7242:                
1.279     brouard  7243:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7244:       * p.j overall mortality formula 49 but computed directly because
                   7245:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7246:       * wix is independent of theta.
                   7247:       */
1.218     brouard  7248:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7249:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7250:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7251:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7252:         varppt[j][i]=doldmp[j][i];
                   7253:      /* end ppptj */
                   7254:      /*  x centered again */
                   7255:                
1.242     brouard  7256:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7257:                
                   7258:      if (popbased==1) {
                   7259:        if(mobilav ==0){
                   7260:         for(i=1; i<=nlstate;i++)
                   7261:           prlim[i][i]=probs[(int)age][i][ij];
                   7262:        }else{ /* mobilav */ 
                   7263:         for(i=1; i<=nlstate;i++)
                   7264:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7265:        }
                   7266:      }
                   7267:                
                   7268:      /* This for computing probability of death (h=1 means
                   7269:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7270:        as a weighted average of prlim.
                   7271:      */
1.235     brouard  7272:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7273:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7274:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7275:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7276:      }    
                   7277:      /* end probability of death */
                   7278:                
                   7279:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7280:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7281:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7282:        for(i=1; i<=nlstate;i++){
                   7283:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7284:        }
                   7285:      } 
                   7286:      fprintf(ficresprobmorprev,"\n");
                   7287:                
                   7288:      fprintf(ficresvij,"%.0f ",age );
                   7289:      for(i=1; i<=nlstate;i++)
                   7290:        for(j=1; j<=nlstate;j++){
                   7291:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7292:        }
                   7293:      fprintf(ficresvij,"\n");
                   7294:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7295:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7296:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7297:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7298:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7299:    } /* End age */
                   7300:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7301:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7302:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7303:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7304:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7305:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7306:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7307:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7308:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7309:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7310:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7311:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7312:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7313:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7314:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7315:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7316:    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);
                   7317:    /*  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  7318:     */
1.218     brouard  7319:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7320:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7321: 
1.218     brouard  7322:    free_vector(xp,1,npar);
                   7323:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7324:    free_matrix(dnewm,1,nlstate,1,npar);
                   7325:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7326:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7327:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7328:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7329:    fclose(ficresprobmorprev);
                   7330:    fflush(ficgp);
                   7331:    fflush(fichtm); 
                   7332:  }  /* end varevsij */
1.126     brouard  7333: 
                   7334: /************ Variance of prevlim ******************/
1.269     brouard  7335:  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  7336: {
1.205     brouard  7337:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7338:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7339: 
1.268     brouard  7340:   double **dnewmpar,**doldm;
1.126     brouard  7341:   int i, j, nhstepm, hstepm;
                   7342:   double *xp;
                   7343:   double *gp, *gm;
                   7344:   double **gradg, **trgradg;
1.208     brouard  7345:   double **mgm, **mgp;
1.126     brouard  7346:   double age,agelim;
                   7347:   int theta;
                   7348:   
                   7349:   pstamp(ficresvpl);
1.288     brouard  7350:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7351:   fprintf(ficresvpl,"# Age ");
                   7352:   if(nresult >=1)
                   7353:     fprintf(ficresvpl," Result# ");
1.126     brouard  7354:   for(i=1; i<=nlstate;i++)
                   7355:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7356:   fprintf(ficresvpl,"\n");
                   7357: 
                   7358:   xp=vector(1,npar);
1.268     brouard  7359:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7360:   doldm=matrix(1,nlstate,1,nlstate);
                   7361:   
                   7362:   hstepm=1*YEARM; /* Every year of age */
                   7363:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7364:   agelim = AGESUP;
                   7365:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7366:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7367:     if (stepm >= YEARM) hstepm=1;
                   7368:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7369:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7370:     mgp=matrix(1,npar,1,nlstate);
                   7371:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7372:     gp=vector(1,nlstate);
                   7373:     gm=vector(1,nlstate);
                   7374: 
                   7375:     for(theta=1; theta <=npar; theta++){
                   7376:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7377:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7378:       }
1.288     brouard  7379:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7380:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7381:       /* else */
                   7382:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7383:       for(i=1;i<=nlstate;i++){
1.126     brouard  7384:        gp[i] = prlim[i][i];
1.208     brouard  7385:        mgp[theta][i] = prlim[i][i];
                   7386:       }
1.126     brouard  7387:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7388:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7389:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7390:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7391:       /* else */
                   7392:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7393:       for(i=1;i<=nlstate;i++){
1.126     brouard  7394:        gm[i] = prlim[i][i];
1.208     brouard  7395:        mgm[theta][i] = prlim[i][i];
                   7396:       }
1.126     brouard  7397:       for(i=1;i<=nlstate;i++)
                   7398:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7399:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7400:     } /* End theta */
                   7401: 
                   7402:     trgradg =matrix(1,nlstate,1,npar);
                   7403: 
                   7404:     for(j=1; j<=nlstate;j++)
                   7405:       for(theta=1; theta <=npar; theta++)
                   7406:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7407:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7408:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7409:     /*   for(j=1; j<=nlstate;j++){ */
                   7410:     /*         printf(" %d ",j); */
                   7411:     /*         for(theta=1; theta <=npar; theta++) */
                   7412:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7413:     /*         printf("\n "); */
                   7414:     /*   } */
                   7415:     /* } */
                   7416:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7417:     /*   printf("\n gradg %d ",(int)age); */
                   7418:     /*   for(j=1; j<=nlstate;j++){ */
                   7419:     /*         printf("%d ",j); */
                   7420:     /*         for(theta=1; theta <=npar; theta++) */
                   7421:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7422:     /*         printf("\n "); */
                   7423:     /*   } */
                   7424:     /* } */
1.126     brouard  7425: 
                   7426:     for(i=1;i<=nlstate;i++)
                   7427:       varpl[i][(int)age] =0.;
1.209     brouard  7428:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7429:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7430:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7431:     }else{
1.268     brouard  7432:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7433:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7434:     }
1.126     brouard  7435:     for(i=1;i<=nlstate;i++)
                   7436:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7437: 
                   7438:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7439:     if(nresult >=1)
                   7440:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7441:     for(i=1; i<=nlstate;i++){
1.126     brouard  7442:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7443:       /* for(j=1;j<=nlstate;j++) */
                   7444:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7445:     }
1.126     brouard  7446:     fprintf(ficresvpl,"\n");
                   7447:     free_vector(gp,1,nlstate);
                   7448:     free_vector(gm,1,nlstate);
1.208     brouard  7449:     free_matrix(mgm,1,npar,1,nlstate);
                   7450:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7451:     free_matrix(gradg,1,npar,1,nlstate);
                   7452:     free_matrix(trgradg,1,nlstate,1,npar);
                   7453:   } /* End age */
                   7454: 
                   7455:   free_vector(xp,1,npar);
                   7456:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7457:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7458: 
                   7459: }
                   7460: 
                   7461: 
                   7462: /************ Variance of backprevalence limit ******************/
1.269     brouard  7463:  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  7464: {
                   7465:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7466:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7467: 
                   7468:   double **dnewmpar,**doldm;
                   7469:   int i, j, nhstepm, hstepm;
                   7470:   double *xp;
                   7471:   double *gp, *gm;
                   7472:   double **gradg, **trgradg;
                   7473:   double **mgm, **mgp;
                   7474:   double age,agelim;
                   7475:   int theta;
                   7476:   
                   7477:   pstamp(ficresvbl);
                   7478:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7479:   fprintf(ficresvbl,"# Age ");
                   7480:   if(nresult >=1)
                   7481:     fprintf(ficresvbl," Result# ");
                   7482:   for(i=1; i<=nlstate;i++)
                   7483:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7484:   fprintf(ficresvbl,"\n");
                   7485: 
                   7486:   xp=vector(1,npar);
                   7487:   dnewmpar=matrix(1,nlstate,1,npar);
                   7488:   doldm=matrix(1,nlstate,1,nlstate);
                   7489:   
                   7490:   hstepm=1*YEARM; /* Every year of age */
                   7491:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7492:   agelim = AGEINF;
                   7493:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7494:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7495:     if (stepm >= YEARM) hstepm=1;
                   7496:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7497:     gradg=matrix(1,npar,1,nlstate);
                   7498:     mgp=matrix(1,npar,1,nlstate);
                   7499:     mgm=matrix(1,npar,1,nlstate);
                   7500:     gp=vector(1,nlstate);
                   7501:     gm=vector(1,nlstate);
                   7502: 
                   7503:     for(theta=1; theta <=npar; theta++){
                   7504:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7505:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7506:       }
                   7507:       if(mobilavproj > 0 )
                   7508:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7509:       else
                   7510:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7511:       for(i=1;i<=nlstate;i++){
                   7512:        gp[i] = bprlim[i][i];
                   7513:        mgp[theta][i] = bprlim[i][i];
                   7514:       }
                   7515:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7516:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7517:        if(mobilavproj > 0 )
                   7518:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7519:        else
                   7520:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7521:       for(i=1;i<=nlstate;i++){
                   7522:        gm[i] = bprlim[i][i];
                   7523:        mgm[theta][i] = bprlim[i][i];
                   7524:       }
                   7525:       for(i=1;i<=nlstate;i++)
                   7526:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7527:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7528:     } /* End theta */
                   7529: 
                   7530:     trgradg =matrix(1,nlstate,1,npar);
                   7531: 
                   7532:     for(j=1; j<=nlstate;j++)
                   7533:       for(theta=1; theta <=npar; theta++)
                   7534:        trgradg[j][theta]=gradg[theta][j];
                   7535:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7536:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7537:     /*   for(j=1; j<=nlstate;j++){ */
                   7538:     /*         printf(" %d ",j); */
                   7539:     /*         for(theta=1; theta <=npar; theta++) */
                   7540:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7541:     /*         printf("\n "); */
                   7542:     /*   } */
                   7543:     /* } */
                   7544:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7545:     /*   printf("\n gradg %d ",(int)age); */
                   7546:     /*   for(j=1; j<=nlstate;j++){ */
                   7547:     /*         printf("%d ",j); */
                   7548:     /*         for(theta=1; theta <=npar; theta++) */
                   7549:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7550:     /*         printf("\n "); */
                   7551:     /*   } */
                   7552:     /* } */
                   7553: 
                   7554:     for(i=1;i<=nlstate;i++)
                   7555:       varbpl[i][(int)age] =0.;
                   7556:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7557:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7558:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7559:     }else{
                   7560:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7561:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7562:     }
                   7563:     for(i=1;i<=nlstate;i++)
                   7564:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7565: 
                   7566:     fprintf(ficresvbl,"%.0f ",age );
                   7567:     if(nresult >=1)
                   7568:       fprintf(ficresvbl,"%d ",nres );
                   7569:     for(i=1; i<=nlstate;i++)
                   7570:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7571:     fprintf(ficresvbl,"\n");
                   7572:     free_vector(gp,1,nlstate);
                   7573:     free_vector(gm,1,nlstate);
                   7574:     free_matrix(mgm,1,npar,1,nlstate);
                   7575:     free_matrix(mgp,1,npar,1,nlstate);
                   7576:     free_matrix(gradg,1,npar,1,nlstate);
                   7577:     free_matrix(trgradg,1,nlstate,1,npar);
                   7578:   } /* End age */
                   7579: 
                   7580:   free_vector(xp,1,npar);
                   7581:   free_matrix(doldm,1,nlstate,1,npar);
                   7582:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7583: 
                   7584: }
                   7585: 
                   7586: /************ Variance of one-step probabilities  ******************/
                   7587: 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  7588:  {
                   7589:    int i, j=0,  k1, l1, tj;
                   7590:    int k2, l2, j1,  z1;
                   7591:    int k=0, l;
                   7592:    int first=1, first1, first2;
1.326     brouard  7593:    int nres=0; /* New */
1.222     brouard  7594:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7595:    double **dnewm,**doldm;
                   7596:    double *xp;
                   7597:    double *gp, *gm;
                   7598:    double **gradg, **trgradg;
                   7599:    double **mu;
                   7600:    double age, cov[NCOVMAX+1];
                   7601:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7602:    int theta;
                   7603:    char fileresprob[FILENAMELENGTH];
                   7604:    char fileresprobcov[FILENAMELENGTH];
                   7605:    char fileresprobcor[FILENAMELENGTH];
                   7606:    double ***varpij;
                   7607: 
                   7608:    strcpy(fileresprob,"PROB_"); 
                   7609:    strcat(fileresprob,fileres);
                   7610:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7611:      printf("Problem with resultfile: %s\n", fileresprob);
                   7612:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7613:    }
                   7614:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7615:    strcat(fileresprobcov,fileresu);
                   7616:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7617:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7618:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7619:    }
                   7620:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7621:    strcat(fileresprobcor,fileresu);
                   7622:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7623:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7624:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7625:    }
                   7626:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7627:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7628:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7629:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7630:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7631:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7632:    pstamp(ficresprob);
                   7633:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7634:    fprintf(ficresprob,"# Age");
                   7635:    pstamp(ficresprobcov);
                   7636:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7637:    fprintf(ficresprobcov,"# Age");
                   7638:    pstamp(ficresprobcor);
                   7639:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7640:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7641: 
                   7642: 
1.222     brouard  7643:    for(i=1; i<=nlstate;i++)
                   7644:      for(j=1; j<=(nlstate+ndeath);j++){
                   7645:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7646:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7647:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7648:      }  
                   7649:    /* fprintf(ficresprob,"\n");
                   7650:       fprintf(ficresprobcov,"\n");
                   7651:       fprintf(ficresprobcor,"\n");
                   7652:    */
                   7653:    xp=vector(1,npar);
                   7654:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7655:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7656:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7657:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7658:    first=1;
                   7659:    fprintf(ficgp,"\n# Routine varprob");
                   7660:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7661:    fprintf(fichtm,"\n");
                   7662: 
1.288     brouard  7663:    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  7664:    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);
                   7665:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7666: and drawn. It helps understanding how is the covariance between two incidences.\
                   7667:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7668:    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  7669: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7670: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7671: standard deviations wide on each axis. <br>\
                   7672:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7673:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7674: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7675: 
1.222     brouard  7676:    cov[1]=1;
                   7677:    /* tj=cptcoveff; */
1.225     brouard  7678:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7679:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7680:    j1=0;
1.332     brouard  7681: 
                   7682:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7683:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7684:      /* 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  7685:      if(tj != 1 && TKresult[nres]!= j1)
                   7686:        continue;
                   7687: 
                   7688:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7689:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7690:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7691:      if  (cptcovn>0) {
1.334     brouard  7692:        fprintf(ficresprob, "\n#********** Variable ");
                   7693:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7694:        fprintf(ficgp, "\n#********** Variable ");
                   7695:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7696:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7697: 
                   7698:        /* Including quantitative variables of the resultline to be done */
                   7699:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  7700:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7701:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7702:         /* 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  7703:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7704:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7705:             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  */
                   7706:             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  */
                   7707:             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  */
                   7708:             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  */
                   7709:             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  */
                   7710:             fprintf(ficresprob,"fixed ");
                   7711:             fprintf(ficresprobcov,"fixed ");
                   7712:             fprintf(ficgp,"fixed ");
                   7713:             fprintf(fichtmcov,"fixed ");
                   7714:             fprintf(ficresprobcor,"fixed ");
                   7715:           }else{
                   7716:             fprintf(ficresprob,"varyi ");
                   7717:             fprintf(ficresprobcov,"varyi ");
                   7718:             fprintf(ficgp,"varyi ");
                   7719:             fprintf(fichtmcov,"varyi ");
                   7720:             fprintf(ficresprobcor,"varyi ");
                   7721:           }
                   7722:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7723:           /* For each selected (single) quantitative value */
1.337     brouard  7724:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7725:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7726:             fprintf(ficresprob,"fixed ");
                   7727:             fprintf(ficresprobcov,"fixed ");
                   7728:             fprintf(ficgp,"fixed ");
                   7729:             fprintf(fichtmcov,"fixed ");
                   7730:             fprintf(ficresprobcor,"fixed ");
                   7731:           }else{
                   7732:             fprintf(ficresprob,"varyi ");
                   7733:             fprintf(ficresprobcov,"varyi ");
                   7734:             fprintf(ficgp,"varyi ");
                   7735:             fprintf(fichtmcov,"varyi ");
                   7736:             fprintf(ficresprobcor,"varyi ");
                   7737:           }
                   7738:         }else{
                   7739:           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 */
                   7740:           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 */
                   7741:           exit(1);
                   7742:         }
                   7743:        } /* End loop on variable of this resultline */
                   7744:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7745:        fprintf(ficresprob, "**********\n#\n");
                   7746:        fprintf(ficresprobcov, "**********\n#\n");
                   7747:        fprintf(ficgp, "**********\n#\n");
                   7748:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7749:        fprintf(ficresprobcor, "**********\n#");    
                   7750:        if(invalidvarcomb[j1]){
                   7751:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7752:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7753:         continue;
                   7754:        }
                   7755:      }
                   7756:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7757:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7758:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7759:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7760:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7761:        cov[2]=age;
                   7762:        if(nagesqr==1)
                   7763:         cov[3]= age*age;
1.334     brouard  7764:        /* New code end of combination but for each resultline */
                   7765:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  7766:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  7767:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7768:         }else{
1.334     brouard  7769:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7770:         }
1.334     brouard  7771:        }/* End of loop on model equation */
                   7772: /* Old code */
                   7773:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7774:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7775:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7776:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7777:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7778:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7779:        /*                                                                  * 1  1 1 1 1 */
                   7780:        /*                                                                  * 2  2 1 1 1 */
                   7781:        /*                                                                  * 3  1 2 1 1 */
                   7782:        /*                                                                  *\/ */
                   7783:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7784:        /* } */
                   7785:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7786:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7787:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7788:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7789:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7790:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7791:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7792:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7793:        /*         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]); */
                   7794:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7795:        /*         /\* exit(1); *\/ */
                   7796:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7797:        /*       } */
                   7798:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7799:        /* } */
                   7800:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7801:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7802:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7803:        /*           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]])]; */
                   7804:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7805:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7806:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7807:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7808:        /*         } */
                   7809:        /*       }else{ */
                   7810:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7811:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7812:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7813:        /*         }else{ */
                   7814:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7815:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7816:        /*         } */
                   7817:        /*       } */
                   7818:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7819:        /* } */                 
1.326     brouard  7820: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7821:        for(theta=1; theta <=npar; theta++){
                   7822:         for(i=1; i<=npar; i++)
                   7823:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7824:                                
1.222     brouard  7825:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7826:                                
1.222     brouard  7827:         k=0;
                   7828:         for(i=1; i<= (nlstate); i++){
                   7829:           for(j=1; j<=(nlstate+ndeath);j++){
                   7830:             k=k+1;
                   7831:             gp[k]=pmmij[i][j];
                   7832:           }
                   7833:         }
1.220     brouard  7834:                                
1.222     brouard  7835:         for(i=1; i<=npar; i++)
                   7836:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7837:                                
1.222     brouard  7838:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7839:         k=0;
                   7840:         for(i=1; i<=(nlstate); i++){
                   7841:           for(j=1; j<=(nlstate+ndeath);j++){
                   7842:             k=k+1;
                   7843:             gm[k]=pmmij[i][j];
                   7844:           }
                   7845:         }
1.220     brouard  7846:                                
1.222     brouard  7847:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7848:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7849:        }
1.126     brouard  7850: 
1.222     brouard  7851:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7852:         for(theta=1; theta <=npar; theta++)
                   7853:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7854:                        
1.222     brouard  7855:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7856:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7857:                        
1.222     brouard  7858:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7859:                        
1.222     brouard  7860:        k=0;
                   7861:        for(i=1; i<=(nlstate); i++){
                   7862:         for(j=1; j<=(nlstate+ndeath);j++){
                   7863:           k=k+1;
                   7864:           mu[k][(int) age]=pmmij[i][j];
                   7865:         }
                   7866:        }
                   7867:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7868:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7869:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7870:                        
1.222     brouard  7871:        /*printf("\n%d ",(int)age);
                   7872:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7873:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7874:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7875:         }*/
1.220     brouard  7876:                        
1.222     brouard  7877:        fprintf(ficresprob,"\n%d ",(int)age);
                   7878:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7879:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7880:                        
1.222     brouard  7881:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7882:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7883:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7884:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7885:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7886:        }
                   7887:        i=0;
                   7888:        for (k=1; k<=(nlstate);k++){
                   7889:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7890:           i++;
                   7891:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7892:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7893:           for (j=1; j<=i;j++){
                   7894:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7895:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7896:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7897:           }
                   7898:         }
                   7899:        }/* end of loop for state */
                   7900:      } /* end of loop for age */
                   7901:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7902:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7903:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7904:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7905:     
                   7906:      /* Confidence intervalle of pij  */
                   7907:      /*
                   7908:        fprintf(ficgp,"\nunset parametric;unset label");
                   7909:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7910:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7911:        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);
                   7912:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7913:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7914:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7915:      */
                   7916:                
                   7917:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7918:      first1=1;first2=2;
                   7919:      for (k2=1; k2<=(nlstate);k2++){
                   7920:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7921:         if(l2==k2) continue;
                   7922:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7923:         for (k1=1; k1<=(nlstate);k1++){
                   7924:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7925:             if(l1==k1) continue;
                   7926:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7927:             if(i<=j) continue;
                   7928:             for (age=bage; age<=fage; age ++){ 
                   7929:               if ((int)age %5==0){
                   7930:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7931:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7932:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7933:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7934:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7935:                 c12=cv12/sqrt(v1*v2);
                   7936:                 /* Computing eigen value of matrix of covariance */
                   7937:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7938:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7939:                 if ((lc2 <0) || (lc1 <0) ){
                   7940:                   if(first2==1){
                   7941:                     first1=0;
                   7942:                     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);
                   7943:                   }
                   7944:                   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);
                   7945:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7946:                   /* lc2=fabs(lc2); */
                   7947:                 }
1.220     brouard  7948:                                                                
1.222     brouard  7949:                 /* Eigen vectors */
1.280     brouard  7950:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7951:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7952:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7953:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7954:                 }else
                   7955:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7956:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7957:                 v21=(lc1-v1)/cv12*v11;
                   7958:                 v12=-v21;
                   7959:                 v22=v11;
                   7960:                 tnalp=v21/v11;
                   7961:                 if(first1==1){
                   7962:                   first1=0;
                   7963:                   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);
                   7964:                 }
                   7965:                 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);
                   7966:                 /*printf(fignu*/
                   7967:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7968:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7969:                 if(first==1){
                   7970:                   first=0;
                   7971:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7972:                   fprintf(ficgp,"\nset parametric;unset label");
                   7973:                   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);
                   7974:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7975:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7976:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7977: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7978:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7979:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7980:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7981:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7982:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7983:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7984:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7985:                   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  7986:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7987:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7988:                 }else{
                   7989:                   first=0;
                   7990:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7991:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7992:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7993:                   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  7994:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7995:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7996:                 }/* if first */
                   7997:               } /* age mod 5 */
                   7998:             } /* end loop age */
                   7999:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8000:             first=1;
                   8001:           } /*l12 */
                   8002:         } /* k12 */
                   8003:        } /*l1 */
                   8004:      }/* k1 */
1.332     brouard  8005:    }  /* loop on combination of covariates j1 */
1.326     brouard  8006:    } /* loop on nres */
1.222     brouard  8007:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8008:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8009:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8010:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8011:    free_vector(xp,1,npar);
                   8012:    fclose(ficresprob);
                   8013:    fclose(ficresprobcov);
                   8014:    fclose(ficresprobcor);
                   8015:    fflush(ficgp);
                   8016:    fflush(fichtmcov);
                   8017:  }
1.126     brouard  8018: 
                   8019: 
                   8020: /******************* Printing html file ***********/
1.201     brouard  8021: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8022:                  int lastpass, int stepm, int weightopt, char model[],\
                   8023:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  8024:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8025:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8026:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  8027:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  8028:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  8029:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8030:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8031: </ul>");
1.319     brouard  8032: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8033: /* </ul>", model); */
1.214     brouard  8034:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8035:    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",
                   8036:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  8037:    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  8038:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8039:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  8040:    fprintf(fichtm,"\
                   8041:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  8042:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  8043:    fprintf(fichtm,"\
1.217     brouard  8044:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8045:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8046:    fprintf(fichtm,"\
1.288     brouard  8047:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8048:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  8049:    fprintf(fichtm,"\
1.288     brouard  8050:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  8051:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8052:    fprintf(fichtm,"\
1.211     brouard  8053:  - (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  8054:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  8055:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  8056:    if(prevfcast==1){
                   8057:      fprintf(fichtm,"\
                   8058:  - Prevalence projections by age and states:                           \
1.201     brouard  8059:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  8060:    }
1.126     brouard  8061: 
                   8062: 
1.225     brouard  8063:    m=pow(2,cptcoveff);
1.222     brouard  8064:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8065: 
1.317     brouard  8066:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  8067: 
                   8068:    jj1=0;
                   8069: 
                   8070:    fprintf(fichtm," \n<ul>");
1.337     brouard  8071:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8072:      /* k1=nres; */
1.338     brouard  8073:      k1=TKresult[nres];
                   8074:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  8075:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8076:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8077:    /*     continue; */
1.264     brouard  8078:      jj1++;
                   8079:      if (cptcovn > 0) {
                   8080:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  8081:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8082:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8083:        }
1.337     brouard  8084:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8085:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8086:        /* } */
                   8087:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8088:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8089:        /* } */
1.264     brouard  8090:        fprintf(fichtm,"\">");
                   8091:        
                   8092:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8093:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8094:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8095:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8096:        }
1.337     brouard  8097:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8098:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8099:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8100:        /* } */
                   8101:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8102:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8103:        /* } */
1.264     brouard  8104:        if(invalidvarcomb[k1]){
                   8105:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8106:         continue;
                   8107:        }
                   8108:        fprintf(fichtm,"</a></li>");
                   8109:      } /* cptcovn >0 */
                   8110:    }
1.317     brouard  8111:    fprintf(fichtm," \n</ul>");
1.264     brouard  8112: 
1.222     brouard  8113:    jj1=0;
1.237     brouard  8114: 
1.337     brouard  8115:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8116:      /* k1=nres; */
1.338     brouard  8117:      k1=TKresult[nres];
                   8118:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8119:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8120:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8121:    /*     continue; */
1.220     brouard  8122: 
1.222     brouard  8123:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8124:      jj1++;
                   8125:      if (cptcovn > 0) {
1.264     brouard  8126:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  8127:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8128:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  8129:        }
1.337     brouard  8130:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8131:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8132:        /* } */
1.264     brouard  8133:        fprintf(fichtm,"\"</a>");
                   8134:  
1.222     brouard  8135:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8136:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8137:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8138:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8139:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8140:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  8141:        }
1.230     brouard  8142:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  8143:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  8144:        if(invalidvarcomb[k1]){
                   8145:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8146:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8147:         continue;
                   8148:        }
                   8149:      }
                   8150:      /* aij, bij */
1.259     brouard  8151:      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  8152: <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  8153:      /* Pij */
1.241     brouard  8154:      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> \
                   8155: <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  8156:      /* Quasi-incidences */
                   8157:      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  8158:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  8159:  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  8160: 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> \
                   8161: <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  8162:      /* Survival functions (period) in state j */
                   8163:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8164:        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);
                   8165:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8166:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  8167:      }
                   8168:      /* State specific survival functions (period) */
                   8169:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  8170:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8171:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  8172:  <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);
                   8173:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8174:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  8175:      }
1.288     brouard  8176:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  8177:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  8178:        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  8179:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  8180:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  8181:      }
1.296     brouard  8182:      if(prevbcast==1){
1.288     brouard  8183:        /* Backward prevalence in each health state */
1.222     brouard  8184:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  8185:         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);
                   8186:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8187:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  8188:        }
1.217     brouard  8189:      }
1.222     brouard  8190:      if(prevfcast==1){
1.288     brouard  8191:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  8192:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  8193:         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);
                   8194:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8195:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8196:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  8197:        }
                   8198:      }
1.296     brouard  8199:      if(prevbcast==1){
1.268     brouard  8200:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8201:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  8202:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8203:  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 \
                   8204:  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  8205: 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);
                   8206:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8207:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  8208:        }
                   8209:      }
1.220     brouard  8210:         
1.222     brouard  8211:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  8212:        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);
                   8213:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8214:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  8215:      }
                   8216:      /* } /\* end i1 *\/ */
1.337     brouard  8217:    }/* End k1=nres */
1.222     brouard  8218:    fprintf(fichtm,"</ul>");
1.126     brouard  8219: 
1.222     brouard  8220:    fprintf(fichtm,"\
1.126     brouard  8221: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  8222:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  8223:  - 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  8224: But because parameters are usually highly correlated (a higher incidence of disability \
                   8225: and a higher incidence of recovery can give very close observed transition) it might \
                   8226: be very useful to look not only at linear confidence intervals estimated from the \
                   8227: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8228: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8229: covariance matrix of the one-step probabilities. \
                   8230: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  8231: 
1.222     brouard  8232:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8233:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8234:    fprintf(fichtm,"\
1.126     brouard  8235:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8236:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  8237: 
1.222     brouard  8238:    fprintf(fichtm,"\
1.126     brouard  8239:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8240:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8241:    fprintf(fichtm,"\
1.126     brouard  8242:  - 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): \
                   8243:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8244:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8245:    fprintf(fichtm,"\
1.126     brouard  8246:  - (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): \
                   8247:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8248:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8249:    fprintf(fichtm,"\
1.288     brouard  8250:  - 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  8251:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8252:    fprintf(fichtm,"\
1.128     brouard  8253:  - 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  8254:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8255:    fprintf(fichtm,"\
1.288     brouard  8256:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8257:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8258: 
                   8259: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8260: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8261: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8262: /*     <br>",fileres,fileres,fileres,fileres); */
                   8263: /*  else  */
1.338     brouard  8264: /*    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  8265:    fflush(fichtm);
1.126     brouard  8266: 
1.225     brouard  8267:    m=pow(2,cptcoveff);
1.222     brouard  8268:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8269: 
1.317     brouard  8270:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8271: 
                   8272:   jj1=0;
                   8273: 
                   8274:    fprintf(fichtm," \n<ul>");
1.337     brouard  8275:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8276:      /* k1=nres; */
1.338     brouard  8277:      k1=TKresult[nres];
1.337     brouard  8278:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8279:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8280:      /*   continue; */
1.317     brouard  8281:      jj1++;
                   8282:      if (cptcovn > 0) {
                   8283:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8284:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8285:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8286:        }
                   8287:        fprintf(fichtm,"\">");
                   8288:        
                   8289:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8290:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8291:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8292:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8293:        }
                   8294:        if(invalidvarcomb[k1]){
                   8295:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8296:         continue;
                   8297:        }
                   8298:        fprintf(fichtm,"</a></li>");
                   8299:      } /* cptcovn >0 */
1.337     brouard  8300:    } /* End nres */
1.317     brouard  8301:    fprintf(fichtm," \n</ul>");
                   8302: 
1.222     brouard  8303:    jj1=0;
1.237     brouard  8304: 
1.241     brouard  8305:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8306:      /* k1=nres; */
1.338     brouard  8307:      k1=TKresult[nres];
                   8308:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8309:      /* for(k1=1; k1<=m;k1++){ */
                   8310:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8311:      /*   continue; */
1.222     brouard  8312:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8313:      jj1++;
1.126     brouard  8314:      if (cptcovn > 0) {
1.317     brouard  8315:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8316:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8317:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8318:        }
                   8319:        fprintf(fichtm,"\"</a>");
                   8320:        
1.126     brouard  8321:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8322:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8323:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8324:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8325:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8326:        }
1.237     brouard  8327: 
1.338     brouard  8328:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8329: 
1.222     brouard  8330:        if(invalidvarcomb[k1]){
                   8331:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8332:         continue;
                   8333:        }
1.337     brouard  8334:      } /* If cptcovn >0 */
1.126     brouard  8335:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8336:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8337: 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);
                   8338:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8339:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8340:      }
                   8341:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8342: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8343: true period expectancies (those weighted with period prevalences are also\
                   8344:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8345:  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);
                   8346:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8347:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8348:      /* } /\* end i1 *\/ */
1.241     brouard  8349:   }/* End nres */
1.222     brouard  8350:    fprintf(fichtm,"</ul>");
                   8351:    fflush(fichtm);
1.126     brouard  8352: }
                   8353: 
                   8354: /******************* Gnuplot file **************/
1.296     brouard  8355: 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  8356: 
                   8357:   char dirfileres[132],optfileres[132];
1.264     brouard  8358:   char gplotcondition[132], gplotlabel[132];
1.343     brouard  8359:   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  8360:   int lv=0, vlv=0, kl=0;
1.130     brouard  8361:   int ng=0;
1.201     brouard  8362:   int vpopbased;
1.223     brouard  8363:   int ioffset; /* variable offset for columns */
1.270     brouard  8364:   int iyearc=1; /* variable column for year of projection  */
                   8365:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8366:   int nres=0; /* Index of resultline */
1.266     brouard  8367:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8368: 
1.126     brouard  8369: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8370: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8371: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8372: /*   } */
                   8373: 
                   8374:   /*#ifdef windows */
                   8375:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8376:   /*#endif */
1.225     brouard  8377:   m=pow(2,cptcoveff);
1.126     brouard  8378: 
1.274     brouard  8379:   /* diagram of the model */
                   8380:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8381:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8382:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8383:   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);
                   8384: 
1.343     brouard  8385:   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  8386:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8387:   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);
                   8388:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8389:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8390:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8391:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8392: 
1.202     brouard  8393:   /* Contribution to likelihood */
                   8394:   /* Plot the probability implied in the likelihood */
1.223     brouard  8395:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8396:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8397:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8398:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8399: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8400:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8401: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8402:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8403:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8404:   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));
                   8405:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8406:   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));
                   8407:   for (i=1; i<= nlstate ; i ++) {
                   8408:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8409:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8410:     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);
                   8411:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8412:       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);
                   8413:     }
                   8414:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8415:   }
                   8416:   /* 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 */               
                   8417:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8418:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8419:   fprintf(ficgp,"\nset out;unset log\n");
                   8420:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8421: 
1.343     brouard  8422:   /* Plot the probability implied in the likelihood by covariate value */
                   8423:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8424:   /* if(debugILK==1){ */
                   8425:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  8426:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8427:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  8428:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
                   8429:     k=19+kf;/*offset because there are 19 columns in the ILK_ file */
1.343     brouard  8430:     for (i=1; i<= nlstate ; i ++) {
                   8431:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8432:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  8433:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8434:        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);
                   8435:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8436:          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);
                   8437:        }
                   8438:       }else{
                   8439:        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);
                   8440:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8441:          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);
                   8442:        }
1.343     brouard  8443:       }
                   8444:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8445:     }
                   8446:   } /* End of each covariate dummy */
                   8447:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8448:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8449:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8450:      *  varying                   1     2                                 3       4        5
                   8451:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8452:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8453:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8454:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8455:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8456:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8457:      */
                   8458:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8459:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8460:     /* 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]); */
                   8461:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8462:       /* printf(" %d",ipos); */
                   8463:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8464:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8465:       kk++; /* Position of the ncovv column in ILK_ */
                   8466:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8467:       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)  */
                   8468:        for (i=1; i<= nlstate ; i ++) {
                   8469:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8470:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8471: 
1.348     brouard  8472:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  8473:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8474:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8475:            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);
                   8476:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8477:              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);
                   8478:            }
                   8479:          }else{
                   8480:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8481:            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);
                   8482:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8483:              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);
                   8484:            }
                   8485:          }
                   8486:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8487:        }
                   8488:       }/* End if dummy varying */
                   8489:     }else{ /*Product */
                   8490:       /* printf("*"); */
                   8491:       /* fprintf(ficresilk,"*"); */
                   8492:     }
                   8493:     iposold=ipos;
                   8494:   } /* For each time varying covariate */
                   8495:   /* } /\* debugILK==1 *\/ */
                   8496:   /* 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 */               
                   8497:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8498:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8499:   fprintf(ficgp,"\nset out;unset log\n");
                   8500:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8501: 
                   8502: 
                   8503:   
1.126     brouard  8504:   strcpy(dirfileres,optionfilefiname);
                   8505:   strcpy(optfileres,"vpl");
1.223     brouard  8506:   /* 1eme*/
1.238     brouard  8507:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8508:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8509:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8510:        k1=TKresult[nres];
1.338     brouard  8511:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8512:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8513:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8514:        /*   continue; */
1.238     brouard  8515:        /* We are interested in selected combination by the resultline */
1.246     brouard  8516:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8517:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8518:        strcpy(gplotlabel,"(");
1.337     brouard  8519:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8520:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8521:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8522: 
                   8523:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8524:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8525:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8526:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8527:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8528:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8529:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8530:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8531:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8532:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8533:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8534:        /* } */
                   8535:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8536:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8537:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8538:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8539:        }
                   8540:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8541:        /* printf("\n#\n"); */
1.238     brouard  8542:        fprintf(ficgp,"\n#\n");
                   8543:        if(invalidvarcomb[k1]){
1.260     brouard  8544:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8545:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8546:          continue;
                   8547:        }
1.235     brouard  8548:       
1.241     brouard  8549:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8550:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8551:        /* 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  8552:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8553:        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);
                   8554:        /* 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); */
                   8555:       /* k1-1 error should be nres-1*/
1.238     brouard  8556:        for (i=1; i<= nlstate ; i ++) {
                   8557:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8558:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8559:        }
1.288     brouard  8560:        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  8561:        for (i=1; i<= nlstate ; i ++) {
                   8562:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8563:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8564:        } 
1.260     brouard  8565:        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  8566:        for (i=1; i<= nlstate ; i ++) {
                   8567:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8568:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8569:        }  
1.265     brouard  8570:        /* 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)); */
                   8571:        
                   8572:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8573:         if(cptcoveff ==0){
1.271     brouard  8574:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8575:        }else{
                   8576:          kl=0;
                   8577:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8578:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8579:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8580:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8581:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8582:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8583:            vlv= nbcode[Tvaraff[k]][lv];
                   8584:            kl++;
                   8585:            /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   8586:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8587:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8588:            /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   8589:            if(k==cptcoveff){
                   8590:              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], \
                   8591:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8592:            }else{
                   8593:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8594:              kl++;
                   8595:            }
                   8596:          } /* end covariate */
                   8597:        } /* end if no covariate */
                   8598: 
1.296     brouard  8599:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8600:          /* 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  8601:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8602:          if(cptcoveff ==0){
1.245     brouard  8603:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8604:          }else{
                   8605:            kl=0;
                   8606:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8607:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8608:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8609:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8610:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8611:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8612:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8613:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8614:              kl++;
1.238     brouard  8615:              /* 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 *\/ */
                   8616:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8617:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8618:              /* ''  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*/
                   8619:              if(k==cptcoveff){
1.245     brouard  8620:                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  8621:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8622:              }else{
1.332     brouard  8623:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8624:                kl++;
                   8625:              }
                   8626:            } /* end covariate */
                   8627:          } /* end if no covariate */
1.296     brouard  8628:          if(prevbcast == 1){
1.268     brouard  8629:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8630:            /* k1-1 error should be nres-1*/
                   8631:            for (i=1; i<= nlstate ; i ++) {
                   8632:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8633:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8634:            }
1.271     brouard  8635:            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  8636:            for (i=1; i<= nlstate ; i ++) {
                   8637:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8638:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8639:            } 
1.276     brouard  8640:            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  8641:            for (i=1; i<= nlstate ; i ++) {
                   8642:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8643:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8644:            } 
1.274     brouard  8645:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8646:          } /* end if backprojcast */
1.296     brouard  8647:        } /* end if prevbcast */
1.276     brouard  8648:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8649:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8650:       } /* nres */
1.337     brouard  8651:     /* } /\* k1 *\/ */
1.201     brouard  8652:   } /* cpt */
1.235     brouard  8653: 
                   8654:   
1.126     brouard  8655:   /*2 eme*/
1.337     brouard  8656:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8657:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8658:       k1=TKresult[nres];
1.338     brouard  8659:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8660:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8661:       /*       continue; */
1.238     brouard  8662:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8663:       strcpy(gplotlabel,"(");
1.337     brouard  8664:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8665:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8666:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8667:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8668:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8669:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8670:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8671:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8672:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8673:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8674:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8675:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8676:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8677:       /* } */
                   8678:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8679:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8680:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8681:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8682:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8683:       }
1.264     brouard  8684:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8685:       fprintf(ficgp,"\n#\n");
1.223     brouard  8686:       if(invalidvarcomb[k1]){
                   8687:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8688:        continue;
                   8689:       }
1.219     brouard  8690:                        
1.241     brouard  8691:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8692:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8693:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8694:        if(vpopbased==0){
1.238     brouard  8695:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8696:        }else
1.238     brouard  8697:          fprintf(ficgp,"\nreplot ");
                   8698:        for (i=1; i<= nlstate+1 ; i ++) {
                   8699:          k=2*i;
1.261     brouard  8700:          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  8701:          for (j=1; j<= nlstate+1 ; j ++) {
                   8702:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8703:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8704:          }   
                   8705:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8706:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8707:          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  8708:          for (j=1; j<= nlstate+1 ; j ++) {
                   8709:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8710:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8711:          }   
                   8712:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8713:          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  8714:          for (j=1; j<= nlstate+1 ; j ++) {
                   8715:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8716:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8717:          }   
                   8718:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8719:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8720:        } /* state */
                   8721:       } /* vpopbased */
1.264     brouard  8722:       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  8723:     } /* end nres */
1.337     brouard  8724:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8725:        
                   8726:        
                   8727:   /*3eme*/
1.337     brouard  8728:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8729:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8730:       k1=TKresult[nres];
1.338     brouard  8731:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8732:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8733:       /*       continue; */
1.238     brouard  8734: 
1.332     brouard  8735:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8736:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8737:        strcpy(gplotlabel,"(");
1.337     brouard  8738:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8739:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8740:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8741:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8742:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8743:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8744:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8745:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8746:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8747:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8748:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8749:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8750:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8751:        /* } */
                   8752:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8753:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8754:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8755:        }
1.264     brouard  8756:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8757:        fprintf(ficgp,"\n#\n");
                   8758:        if(invalidvarcomb[k1]){
                   8759:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8760:          continue;
                   8761:        }
                   8762:                        
                   8763:        /*       k=2+nlstate*(2*cpt-2); */
                   8764:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8765:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8766:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8767:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8768: 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  8769:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8770:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8771:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8772:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8773:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8774:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8775:                                
1.238     brouard  8776:        */
                   8777:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8778:          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  8779:          /*    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  8780:                                
1.238     brouard  8781:        } 
1.261     brouard  8782:        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  8783:       }
1.264     brouard  8784:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8785:     } /* end nres */
1.337     brouard  8786:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8787:   
1.223     brouard  8788:   /* 4eme */
1.201     brouard  8789:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8790:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8791:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8792:       k1=TKresult[nres];
1.338     brouard  8793:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8794:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8795:       /*       continue; */
1.238     brouard  8796:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8797:        strcpy(gplotlabel,"(");
1.337     brouard  8798:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8799:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8800:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8802:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8803:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8804:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8805:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8806:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8807:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8808:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8809:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8810:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8811:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8812:        /* } */
                   8813:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8814:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8815:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8816:        }       
1.264     brouard  8817:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8818:        fprintf(ficgp,"\n#\n");
                   8819:        if(invalidvarcomb[k1]){
                   8820:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8821:          continue;
1.223     brouard  8822:        }
1.238     brouard  8823:       
1.241     brouard  8824:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8825:        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  8826:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8827: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8828:        k=3;
                   8829:        for (i=1; i<= nlstate ; i ++){
                   8830:          if(i==1){
                   8831:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8832:          }else{
                   8833:            fprintf(ficgp,", '' ");
                   8834:          }
                   8835:          l=(nlstate+ndeath)*(i-1)+1;
                   8836:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8837:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8838:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8839:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8840:        } /* nlstate */
1.264     brouard  8841:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8842:       } /* end cpt state*/ 
                   8843:     } /* end nres */
1.337     brouard  8844:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8845: 
1.220     brouard  8846: /* 5eme */
1.201     brouard  8847:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8848:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8849:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8850:       k1=TKresult[nres];
1.338     brouard  8851:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8852:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8853:       /*       continue; */
1.238     brouard  8854:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8855:        strcpy(gplotlabel,"(");
1.238     brouard  8856:        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  8857:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8858:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8859:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8860:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8861:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8862:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8863:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8864:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8865:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8866:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8867:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8868:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8869:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8870:        /* } */
                   8871:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8872:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8873:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8874:        }       
1.264     brouard  8875:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8876:        fprintf(ficgp,"\n#\n");
                   8877:        if(invalidvarcomb[k1]){
                   8878:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8879:          continue;
                   8880:        }
1.227     brouard  8881:       
1.241     brouard  8882:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8883:        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  8884:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8885: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8886:        k=3;
                   8887:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8888:          if(j==1)
                   8889:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8890:          else
                   8891:            fprintf(ficgp,", '' ");
                   8892:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8893:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8894:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8895:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8896:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8897:        } /* nlstate */
                   8898:        fprintf(ficgp,", '' ");
                   8899:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8900:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8901:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8902:          if(j < nlstate)
                   8903:            fprintf(ficgp,"$%d +",k+l);
                   8904:          else
                   8905:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8906:        }
1.264     brouard  8907:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8908:       } /* end cpt state*/ 
1.337     brouard  8909:     /* } /\* end covariate *\/   */
1.238     brouard  8910:   } /* end nres */
1.227     brouard  8911:   
1.220     brouard  8912: /* 6eme */
1.202     brouard  8913:   /* CV preval stable (period) for each covariate */
1.337     brouard  8914:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8915:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8916:      k1=TKresult[nres];
1.338     brouard  8917:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8918:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8919:      /*  continue; */
1.255     brouard  8920:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8921:       strcpy(gplotlabel,"(");      
1.288     brouard  8922:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8923:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8924:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8925:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8926:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8927:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8928:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8929:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8930:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8931:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8932:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8933:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8934:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8935:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8936:       /* } */
                   8937:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8938:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8939:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8940:       }        
1.264     brouard  8941:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8942:       fprintf(ficgp,"\n#\n");
1.223     brouard  8943:       if(invalidvarcomb[k1]){
1.227     brouard  8944:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8945:        continue;
1.223     brouard  8946:       }
1.227     brouard  8947:       
1.241     brouard  8948:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8949:       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  8950:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8951: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8952:       k=3; /* Offset */
1.255     brouard  8953:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8954:        if(i==1)
                   8955:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8956:        else
                   8957:          fprintf(ficgp,", '' ");
1.255     brouard  8958:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8959:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8960:        for (j=2; j<= nlstate ; j ++)
                   8961:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8962:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8963:       } /* nlstate */
1.264     brouard  8964:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8965:     } /* end cpt state*/ 
                   8966:   } /* end covariate */  
1.227     brouard  8967:   
                   8968:   
1.220     brouard  8969: /* 7eme */
1.296     brouard  8970:   if(prevbcast == 1){
1.288     brouard  8971:     /* CV backward prevalence  for each covariate */
1.337     brouard  8972:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8973:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8974:       k1=TKresult[nres];
1.338     brouard  8975:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8976:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8977:       /*       continue; */
1.268     brouard  8978:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8979:        strcpy(gplotlabel,"(");      
1.288     brouard  8980:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8981:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8982:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8983:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8984:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8985:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8986:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8987:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8988:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8989:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8990:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8991:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8992:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8993:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8994:        /* } */
                   8995:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8996:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8997:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8998:        }       
1.264     brouard  8999:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9000:        fprintf(ficgp,"\n#\n");
                   9001:        if(invalidvarcomb[k1]){
                   9002:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9003:          continue;
                   9004:        }
                   9005:        
1.241     brouard  9006:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  9007:        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  9008:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  9009: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  9010:        k=3; /* Offset */
1.268     brouard  9011:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  9012:          if(i==1)
                   9013:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9014:          else
                   9015:            fprintf(ficgp,", '' ");
                   9016:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  9017:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  9018:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9019:          /* 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  9020:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  9021:          /* for (j=2; j<= nlstate ; j ++) */
                   9022:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9023:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  9024:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  9025:        } /* nlstate */
1.264     brouard  9026:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  9027:       } /* end cpt state*/ 
                   9028:     } /* end covariate */  
1.296     brouard  9029:   } /* End if prevbcast */
1.218     brouard  9030:   
1.223     brouard  9031:   /* 8eme */
1.218     brouard  9032:   if(prevfcast==1){
1.288     brouard  9033:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  9034:     
1.337     brouard  9035:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  9036:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9037:       k1=TKresult[nres];
1.338     brouard  9038:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9039:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9040:       /*       continue; */
1.211     brouard  9041:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  9042:        strcpy(gplotlabel,"(");      
1.288     brouard  9043:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  9044:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9045:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9046:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9047:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9048:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9049:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9050:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9051:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9052:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9053:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9054:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9055:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9056:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9057:        /* } */
                   9058:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9059:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9060:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  9061:        }       
1.264     brouard  9062:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  9063:        fprintf(ficgp,"\n#\n");
                   9064:        if(invalidvarcomb[k1]){
                   9065:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9066:          continue;
                   9067:        }
                   9068:        
                   9069:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  9070:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  9071:        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  9072:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  9073: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  9074: 
                   9075:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9076:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9077:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9078:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  9079:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9080:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9081:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9082:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  9083:          if(i==istart){
1.227     brouard  9084:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9085:          }else{
                   9086:            fprintf(ficgp,",\\\n '' ");
                   9087:          }
                   9088:          if(cptcoveff ==0){ /* No covariate */
                   9089:            ioffset=2; /* Age is in 2 */
                   9090:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9091:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9092:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9093:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9094:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  9095:            if(i==nlstate+1){
1.270     brouard  9096:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  9097:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9098:              fprintf(ficgp,",\\\n '' ");
                   9099:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9100:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  9101:                     offyear,                           \
1.268     brouard  9102:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  9103:            }else
1.227     brouard  9104:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9105:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9106:          }else{ /* more than 2 covariates */
1.270     brouard  9107:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9108:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9109:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9110:            iyearc=ioffset-1;
                   9111:            iagec=ioffset;
1.227     brouard  9112:            fprintf(ficgp," u %d:(",ioffset); 
                   9113:            kl=0;
                   9114:            strcpy(gplotcondition,"(");
1.351     brouard  9115:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  9116:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  9117:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9118:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9119:              lv=Tvresult[nres][k];
                   9120:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  9121:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9122:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9123:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  9124:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  9125:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  9126:              kl++;
1.351     brouard  9127:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9128:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  9129:              kl++;
1.351     brouard  9130:              if(k <cptcovs && cptcovs>1)
1.227     brouard  9131:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9132:            }
                   9133:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9134:            /* 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 *\/ */
                   9135:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9136:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9137:            /* ''  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*/
                   9138:            if(i==nlstate+1){
1.270     brouard  9139:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9140:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  9141:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9142:              fprintf(ficgp," u %d:(",iagec); 
                   9143:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9144:                      iyearc, iagec, offyear,                           \
                   9145:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  9146: /*  '' 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  9147:            }else{
                   9148:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9149:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9150:            }
                   9151:          } /* end if covariate */
                   9152:        } /* nlstate */
1.264     brouard  9153:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  9154:       } /* end cpt state*/
                   9155:     } /* end covariate */
                   9156:   } /* End if prevfcast */
1.227     brouard  9157:   
1.296     brouard  9158:   if(prevbcast==1){
1.268     brouard  9159:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9160:     
1.337     brouard  9161:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  9162:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9163:      k1=TKresult[nres];
1.338     brouard  9164:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9165:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9166:        /*      continue; */
1.268     brouard  9167:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9168:        strcpy(gplotlabel,"(");      
                   9169:        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  9170:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9171:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9172:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9173:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9174:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9175:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9176:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9177:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9178:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9179:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9180:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9181:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9182:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9183:        /* } */
                   9184:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9185:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9186:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  9187:        }       
                   9188:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9189:        fprintf(ficgp,"\n#\n");
                   9190:        if(invalidvarcomb[k1]){
                   9191:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9192:          continue;
                   9193:        }
                   9194:        
                   9195:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9196:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9197:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9198:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9199: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9200: 
                   9201:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9202:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9203:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9204:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9205:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9206:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9207:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9208:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9209:          if(i==istart){
                   9210:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9211:          }else{
                   9212:            fprintf(ficgp,",\\\n '' ");
                   9213:          }
1.351     brouard  9214:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9215:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  9216:            ioffset=2; /* Age is in 2 */
                   9217:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9218:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9219:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9220:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9221:            fprintf(ficgp," u %d:(", ioffset); 
                   9222:            if(i==nlstate+1){
1.270     brouard  9223:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  9224:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9225:              fprintf(ficgp,",\\\n '' ");
                   9226:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  9227:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  9228:                     offbyear,                          \
                   9229:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9230:            }else
                   9231:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9232:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9233:          }else{ /* more than 2 covariates */
1.270     brouard  9234:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9235:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9236:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9237:            iyearc=ioffset-1;
                   9238:            iagec=ioffset;
1.268     brouard  9239:            fprintf(ficgp," u %d:(",ioffset); 
                   9240:            kl=0;
                   9241:            strcpy(gplotcondition,"(");
1.337     brouard  9242:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  9243:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  9244:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9245:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9246:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9247:                lv=Tvresult[nres][k];
                   9248:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9249:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9250:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9251:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9252:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9253:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9254:                kl++;
                   9255:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9256:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9257:                kl++;
1.338     brouard  9258:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9259:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9260:              }
1.268     brouard  9261:            }
                   9262:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9263:            /* 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 *\/ */
                   9264:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9265:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9266:            /* ''  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*/
                   9267:            if(i==nlstate+1){
1.270     brouard  9268:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9269:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9270:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9271:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9272:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9273:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9274:                      iyearc,iagec,offbyear,                            \
                   9275:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9276: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9277:            }else{
                   9278:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9279:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9280:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9281:            }
                   9282:          } /* end if covariate */
                   9283:        } /* nlstate */
                   9284:        fprintf(ficgp,"\nset out; unset label;\n");
                   9285:       } /* end cpt state*/
                   9286:     } /* end covariate */
1.296     brouard  9287:   } /* End if prevbcast */
1.268     brouard  9288:   
1.227     brouard  9289:   
1.238     brouard  9290:   /* 9eme writing MLE parameters */
                   9291:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9292:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9293:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9294:     for(k=1; k <=(nlstate+ndeath); k++){
                   9295:       if (k != i) {
1.227     brouard  9296:        fprintf(ficgp,"#   current state %d\n",k);
                   9297:        for(j=1; j <=ncovmodel; j++){
                   9298:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9299:          jk++; 
                   9300:        }
                   9301:        fprintf(ficgp,"\n");
1.126     brouard  9302:       }
                   9303:     }
1.223     brouard  9304:   }
1.187     brouard  9305:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9306:   
1.145     brouard  9307:   /*goto avoid;*/
1.238     brouard  9308:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9309:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9310:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9311:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9312:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9313:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9314:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9315:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9316:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9317:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9318:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9319:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9320:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9321:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9322:   fprintf(ficgp,"#\n");
1.223     brouard  9323:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9324:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9325:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9326:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  9327:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9328:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  9329:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9330:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9331:      /* k1=nres; */
1.338     brouard  9332:       k1=TKresult[nres];
                   9333:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9334:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9335:       strcpy(gplotlabel,"(");
1.276     brouard  9336:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9337:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9338:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9339:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9340:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9341:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9342:       }
                   9343:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9344:       /*       continue; */
                   9345:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9346:       /* strcpy(gplotlabel,"("); */
                   9347:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9348:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9349:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9350:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9351:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9352:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9353:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9354:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9355:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9356:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9357:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9358:       /* } */
                   9359:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9360:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9361:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9362:       /* }      */
1.264     brouard  9363:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9364:       fprintf(ficgp,"\n#\n");
1.264     brouard  9365:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9366:       fprintf(ficgp,"\nset key outside ");
                   9367:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9368:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9369:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9370:       if (ng==1){
                   9371:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9372:        fprintf(ficgp,"\nunset log y");
                   9373:       }else if (ng==2){
                   9374:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9375:        fprintf(ficgp,"\nset log y");
                   9376:       }else if (ng==3){
                   9377:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9378:        fprintf(ficgp,"\nset log y");
                   9379:       }else
                   9380:        fprintf(ficgp,"\nunset title ");
                   9381:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9382:       i=1;
                   9383:       for(k2=1; k2<=nlstate; k2++) {
                   9384:        k3=i;
                   9385:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9386:          if (k != k2){
                   9387:            switch( ng) {
                   9388:            case 1:
                   9389:              if(nagesqr==0)
                   9390:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9391:              else /* nagesqr =1 */
                   9392:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9393:              break;
                   9394:            case 2: /* ng=2 */
                   9395:              if(nagesqr==0)
                   9396:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9397:              else /* nagesqr =1 */
                   9398:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9399:              break;
                   9400:            case 3:
                   9401:              if(nagesqr==0)
                   9402:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9403:              else /* nagesqr =1 */
                   9404:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9405:              break;
                   9406:            }
                   9407:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9408:            ijp=1; /* product no age */
                   9409:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9410:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9411:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9412:              switch(Typevar[j]){
                   9413:              case 1:
                   9414:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9415:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9416:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9417:                      if(DummyV[j]==0){/* Bug valgrind */
                   9418:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9419:                      }else{ /* quantitative */
                   9420:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9421:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9422:                      }
                   9423:                      ij++;
1.268     brouard  9424:                    }
1.237     brouard  9425:                  }
1.329     brouard  9426:                }
                   9427:                break;
                   9428:              case 2:
                   9429:                if(cptcovprod >0){
                   9430:                  if(j==Tprod[ijp]) { /* */ 
                   9431:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9432:                    if(ijp <=cptcovprod) { /* Product */
                   9433:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9434:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9435:                          /* 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)]); */
                   9436:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9437:                        }else{ /* Vn is dummy and Vm is quanti */
                   9438:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9439:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9440:                        }
                   9441:                      }else{ /* Vn*Vm Vn is quanti */
                   9442:                        if(DummyV[Tvard[ijp][2]]==0){
                   9443:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9444:                        }else{ /* Both quanti */
                   9445:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9446:                        }
1.268     brouard  9447:                      }
1.329     brouard  9448:                      ijp++;
1.237     brouard  9449:                    }
1.329     brouard  9450:                  } /* end Tprod */
                   9451:                }
                   9452:                break;
1.349     brouard  9453:              case 3:
                   9454:                if(cptcovdageprod >0){
                   9455:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9456:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  9457:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9458:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9459:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9460:                          /* 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)]); */
                   9461:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9462:                        }else{ /* Vn is dummy and Vm is quanti */
                   9463:                          /* 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  9464:                          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  9465:                        }
1.350     brouard  9466:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  9467:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  9468:                          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  9469:                        }else{ /* Both quanti */
1.350     brouard  9470:                          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  9471:                        }
                   9472:                      }
                   9473:                      ijp++;
                   9474:                    }
                   9475:                    /* } */ /* end Tprod */
                   9476:                }
                   9477:                break;
1.329     brouard  9478:              case 0:
                   9479:                /* simple covariate */
1.264     brouard  9480:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9481:                if(Dummy[j]==0){
                   9482:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9483:                }else{ /* quantitative */
                   9484:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9485:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9486:                }
1.329     brouard  9487:               /* end simple */
                   9488:                break;
                   9489:              default:
                   9490:                break;
                   9491:              } /* end switch */
1.237     brouard  9492:            } /* end j */
1.329     brouard  9493:          }else{ /* k=k2 */
                   9494:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9495:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9496:            }else
                   9497:              i=i-ncovmodel;
1.223     brouard  9498:          }
1.227     brouard  9499:          
1.223     brouard  9500:          if(ng != 1){
                   9501:            fprintf(ficgp,")/(1");
1.227     brouard  9502:            
1.264     brouard  9503:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9504:              if(nagesqr==0)
1.264     brouard  9505:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9506:              else /* nagesqr =1 */
1.264     brouard  9507:                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  9508:               
1.223     brouard  9509:              ij=1;
1.329     brouard  9510:              ijp=1;
                   9511:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9512:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9513:                switch(Typevar[j]){
                   9514:                case 1:
                   9515:                  if(cptcovage >0){ 
                   9516:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9517:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9518:                        if(DummyV[j]==0){/* Bug valgrind */
                   9519:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9520:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9521:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9522:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9523:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9524:                        }else{ /* quantitative */
                   9525:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9526:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9527:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9528:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9529:                        }
                   9530:                        ij++;
                   9531:                      }
                   9532:                    }
                   9533:                  }
                   9534:                  break;
                   9535:                case 2:
                   9536:                  if(cptcovprod >0){
                   9537:                    if(j==Tprod[ijp]) { /* */ 
                   9538:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9539:                      if(ijp <=cptcovprod) { /* Product */
                   9540:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9541:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9542:                            /* 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)]); */
                   9543:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9544:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9545:                          }else{ /* Vn is dummy and Vm is quanti */
                   9546:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9547:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9548:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9549:                          }
                   9550:                        }else{ /* Vn*Vm Vn is quanti */
                   9551:                          if(DummyV[Tvard[ijp][2]]==0){
                   9552:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9553:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9554:                          }else{ /* Both quanti */
                   9555:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9556:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9557:                          } 
                   9558:                        }
                   9559:                        ijp++;
                   9560:                      }
                   9561:                    } /* end Tprod */
                   9562:                  } /* end if */
                   9563:                  break;
1.349     brouard  9564:                case 3:
                   9565:                  if(cptcovdageprod >0){
                   9566:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9567:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9568:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  9569:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9570:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  9571:                            /* 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  9572:                            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  9573:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9574:                          }else{ /* Vn is dummy and Vm is quanti */
                   9575:                            /* 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  9576:                            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  9577:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9578:                          }
                   9579:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  9580:                          if(DummyV[Tvardk[ijp][2]]==0){
                   9581:                            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  9582:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9583:                          }else{ /* Both quanti */
1.350     brouard  9584:                            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  9585:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9586:                          } 
                   9587:                        }
                   9588:                        ijp++;
                   9589:                      }
                   9590:                    /* } /\* end Tprod *\/ */
                   9591:                  } /* end if */
                   9592:                  break;
1.329     brouard  9593:                case 0: 
                   9594:                  /* simple covariate */
                   9595:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9596:                  if(Dummy[j]==0){
                   9597:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9598:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9599:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9600:                  }else{ /* quantitative */
                   9601:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9602:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9603:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9604:                  }
                   9605:                  /* end simple */
                   9606:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9607:                  break;
                   9608:                default:
                   9609:                  break;
                   9610:                } /* end switch */
1.223     brouard  9611:              }
                   9612:              fprintf(ficgp,")");
                   9613:            }
                   9614:            fprintf(ficgp,")");
                   9615:            if(ng ==2)
1.276     brouard  9616:              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  9617:            else /* ng= 3 */
1.276     brouard  9618:              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  9619:           }else{ /* end ng <> 1 */
1.223     brouard  9620:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9621:              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  9622:          }
                   9623:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9624:            fprintf(ficgp,",");
                   9625:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9626:            fprintf(ficgp,",");
                   9627:          i=i+ncovmodel;
                   9628:        } /* end k */
                   9629:       } /* end k2 */
1.276     brouard  9630:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9631:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9632:     } /* end resultline */
1.223     brouard  9633:   } /* end ng */
                   9634:   /* avoid: */
                   9635:   fflush(ficgp); 
1.126     brouard  9636: }  /* end gnuplot */
                   9637: 
                   9638: 
                   9639: /*************** Moving average **************/
1.219     brouard  9640: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9641:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9642:    
1.222     brouard  9643:    int i, cpt, cptcod;
                   9644:    int modcovmax =1;
                   9645:    int mobilavrange, mob;
                   9646:    int iage=0;
1.288     brouard  9647:    int firstA1=0, firstA2=0;
1.222     brouard  9648: 
1.266     brouard  9649:    double sum=0., sumr=0.;
1.222     brouard  9650:    double age;
1.266     brouard  9651:    double *sumnewp, *sumnewm, *sumnewmr;
                   9652:    double *agemingood, *agemaxgood; 
                   9653:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9654:   
                   9655:   
1.278     brouard  9656:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9657:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9658: 
                   9659:    sumnewp = vector(1,ncovcombmax);
                   9660:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9661:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9662:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9663:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9664:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9665:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9666: 
                   9667:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9668:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9669:      sumnewp[cptcod]=0.;
1.266     brouard  9670:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9671:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9672:    }
                   9673:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9674:   
1.266     brouard  9675:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9676:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9677:      else mobilavrange=mobilav;
                   9678:      for (age=bage; age<=fage; age++)
                   9679:        for (i=1; i<=nlstate;i++)
                   9680:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9681:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9682:      /* We keep the original values on the extreme ages bage, fage and for 
                   9683:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9684:        we use a 5 terms etc. until the borders are no more concerned. 
                   9685:      */ 
                   9686:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9687:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9688:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9689:           sumnewm[cptcod]=0.;
                   9690:           for (i=1; i<=nlstate;i++){
1.222     brouard  9691:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9692:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9693:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9694:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9695:             }
                   9696:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9697:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9698:           } /* end i */
                   9699:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9700:         } /* end cptcod */
1.222     brouard  9701:        }/* end age */
                   9702:      }/* end mob */
1.266     brouard  9703:    }else{
                   9704:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9705:      return -1;
1.266     brouard  9706:    }
                   9707: 
                   9708:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9709:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9710:      if(invalidvarcomb[cptcod]){
                   9711:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9712:        continue;
                   9713:      }
1.219     brouard  9714: 
1.266     brouard  9715:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9716:        sumnewm[cptcod]=0.;
                   9717:        sumnewmr[cptcod]=0.;
                   9718:        for (i=1; i<=nlstate;i++){
                   9719:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9720:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9721:        }
                   9722:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9723:         agemingoodr[cptcod]=age;
                   9724:        }
                   9725:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9726:           agemingood[cptcod]=age;
                   9727:        }
                   9728:      } /* age */
                   9729:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9730:        sumnewm[cptcod]=0.;
1.266     brouard  9731:        sumnewmr[cptcod]=0.;
1.222     brouard  9732:        for (i=1; i<=nlstate;i++){
                   9733:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9734:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9735:        }
                   9736:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9737:         agemaxgoodr[cptcod]=age;
1.222     brouard  9738:        }
                   9739:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9740:         agemaxgood[cptcod]=age;
                   9741:        }
                   9742:      } /* age */
                   9743:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9744:      /* but they will change */
1.288     brouard  9745:      firstA1=0;firstA2=0;
1.266     brouard  9746:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9747:        sumnewm[cptcod]=0.;
                   9748:        sumnewmr[cptcod]=0.;
                   9749:        for (i=1; i<=nlstate;i++){
                   9750:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9751:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9752:        }
                   9753:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9754:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9755:           agemaxgoodr[cptcod]=age;  /* age min */
                   9756:           for (i=1; i<=nlstate;i++)
                   9757:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9758:         }else{ /* bad we change the value with the values of good ages */
                   9759:           for (i=1; i<=nlstate;i++){
                   9760:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9761:           } /* i */
                   9762:         } /* end bad */
                   9763:        }else{
                   9764:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9765:           agemaxgood[cptcod]=age;
                   9766:         }else{ /* bad we change the value with the values of good ages */
                   9767:           for (i=1; i<=nlstate;i++){
                   9768:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9769:           } /* i */
                   9770:         } /* end bad */
                   9771:        }/* end else */
                   9772:        sum=0.;sumr=0.;
                   9773:        for (i=1; i<=nlstate;i++){
                   9774:         sum+=mobaverage[(int)age][i][cptcod];
                   9775:         sumr+=probs[(int)age][i][cptcod];
                   9776:        }
                   9777:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9778:         if(!firstA1){
                   9779:           firstA1=1;
                   9780:           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);
                   9781:         }
                   9782:         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  9783:        } /* end bad */
                   9784:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9785:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9786:         if(!firstA2){
                   9787:           firstA2=1;
                   9788:           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);
                   9789:         }
                   9790:         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  9791:        } /* end bad */
                   9792:      }/* age */
1.266     brouard  9793: 
                   9794:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9795:        sumnewm[cptcod]=0.;
1.266     brouard  9796:        sumnewmr[cptcod]=0.;
1.222     brouard  9797:        for (i=1; i<=nlstate;i++){
                   9798:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9799:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9800:        } 
                   9801:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9802:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9803:           agemingoodr[cptcod]=age;
                   9804:           for (i=1; i<=nlstate;i++)
                   9805:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9806:         }else{ /* bad we change the value with the values of good ages */
                   9807:           for (i=1; i<=nlstate;i++){
                   9808:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9809:           } /* i */
                   9810:         } /* end bad */
                   9811:        }else{
                   9812:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9813:           agemingood[cptcod]=age;
                   9814:         }else{ /* bad */
                   9815:           for (i=1; i<=nlstate;i++){
                   9816:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9817:           } /* i */
                   9818:         } /* end bad */
                   9819:        }/* end else */
                   9820:        sum=0.;sumr=0.;
                   9821:        for (i=1; i<=nlstate;i++){
                   9822:         sum+=mobaverage[(int)age][i][cptcod];
                   9823:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9824:        }
1.266     brouard  9825:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9826:         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  9827:        } /* end bad */
                   9828:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9829:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9830:         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  9831:        } /* end bad */
                   9832:      }/* age */
1.266     brouard  9833: 
1.222     brouard  9834:                
                   9835:      for (age=bage; age<=fage; age++){
1.235     brouard  9836:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9837:        sumnewp[cptcod]=0.;
                   9838:        sumnewm[cptcod]=0.;
                   9839:        for (i=1; i<=nlstate;i++){
                   9840:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9841:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9842:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9843:        }
                   9844:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9845:      }
                   9846:      /* printf("\n"); */
                   9847:      /* } */
1.266     brouard  9848: 
1.222     brouard  9849:      /* brutal averaging */
1.266     brouard  9850:      /* for (i=1; i<=nlstate;i++){ */
                   9851:      /*   for (age=1; age<=bage; age++){ */
                   9852:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9853:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9854:      /*   }     */
                   9855:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9856:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9857:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9858:      /*   } */
                   9859:      /* } /\* end i status *\/ */
                   9860:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9861:      /*   for (age=1; age<=AGESUP; age++){ */
                   9862:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9863:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9864:      /*   } */
                   9865:      /* } */
1.222     brouard  9866:    }/* end cptcod */
1.266     brouard  9867:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9868:    free_vector(agemaxgood,1, ncovcombmax);
                   9869:    free_vector(agemingood,1, ncovcombmax);
                   9870:    free_vector(agemingoodr,1, ncovcombmax);
                   9871:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9872:    free_vector(sumnewm,1, ncovcombmax);
                   9873:    free_vector(sumnewp,1, ncovcombmax);
                   9874:    return 0;
                   9875:  }/* End movingaverage */
1.218     brouard  9876:  
1.126     brouard  9877: 
1.296     brouard  9878:  
1.126     brouard  9879: /************** Forecasting ******************/
1.296     brouard  9880: /* 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)*/
                   9881: 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){
                   9882:   /* dateintemean, mean date of interviews
                   9883:      dateprojd, year, month, day of starting projection 
                   9884:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9885:      agemin, agemax range of age
                   9886:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9887:   */
1.296     brouard  9888:   /* double anprojd, mprojd, jprojd; */
                   9889:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9890:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9891:   double agec; /* generic age */
1.296     brouard  9892:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9893:   double *popeffectif,*popcount;
                   9894:   double ***p3mat;
1.218     brouard  9895:   /* double ***mobaverage; */
1.126     brouard  9896:   char fileresf[FILENAMELENGTH];
                   9897: 
                   9898:   agelim=AGESUP;
1.211     brouard  9899:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9900:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9901:      We still use firstpass and lastpass as another selection.
                   9902:   */
1.214     brouard  9903:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9904:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9905:  
1.201     brouard  9906:   strcpy(fileresf,"F_"); 
                   9907:   strcat(fileresf,fileresu);
1.126     brouard  9908:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9909:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9910:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9911:   }
1.235     brouard  9912:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9913:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9914: 
1.225     brouard  9915:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9916: 
                   9917: 
                   9918:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9919:   if (stepm<=12) stepsize=1;
                   9920:   if(estepm < stepm){
                   9921:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9922:   }
1.270     brouard  9923:   else{
                   9924:     hstepm=estepm;   
                   9925:   }
                   9926:   if(estepm > stepm){ /* Yes every two year */
                   9927:     stepsize=2;
                   9928:   }
1.296     brouard  9929:   hstepm=hstepm/stepm;
1.126     brouard  9930: 
1.296     brouard  9931:   
                   9932:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9933:   /*                              fractional in yp1 *\/ */
                   9934:   /* aintmean=yp; */
                   9935:   /* yp2=modf((yp1*12),&yp); */
                   9936:   /* mintmean=yp; */
                   9937:   /* yp1=modf((yp2*30.5),&yp); */
                   9938:   /* jintmean=yp; */
                   9939:   /* if(jintmean==0) jintmean=1; */
                   9940:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9941: 
1.296     brouard  9942: 
                   9943:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9944:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9945:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  9946:   /* i1=pow(2,cptcoveff); */
                   9947:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  9948:   
1.296     brouard  9949:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9950:   
                   9951:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9952:   
1.126     brouard  9953: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  9954:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9955:     k=TKresult[nres];
                   9956:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   9957:     /*  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) *\/ */
                   9958:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   9959:     /*   continue; */
                   9960:     /* if(invalidvarcomb[k]){ */
                   9961:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   9962:     /*   continue; */
                   9963:     /* } */
1.227     brouard  9964:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  9965:     for(j=1;j<=cptcovs;j++){
                   9966:       /* for(j=1;j<=cptcoveff;j++) { */
                   9967:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   9968:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9969:     /* } */
                   9970:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9971:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9972:     /* } */
                   9973:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  9974:     }
1.351     brouard  9975:  
1.227     brouard  9976:     fprintf(ficresf," yearproj age");
                   9977:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9978:       for(i=1; i<=nlstate;i++)               
                   9979:        fprintf(ficresf," p%d%d",i,j);
                   9980:       fprintf(ficresf," wp.%d",j);
                   9981:     }
1.296     brouard  9982:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9983:       fprintf(ficresf,"\n");
1.296     brouard  9984:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9985:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9986:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9987:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9988:        nhstepm = nhstepm/hstepm; 
                   9989:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9990:        oldm=oldms;savm=savms;
1.268     brouard  9991:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9992:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9993:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9994:        for (h=0; h<=nhstepm; h++){
                   9995:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9996:            break;
                   9997:          }
                   9998:        }
                   9999:        fprintf(ficresf,"\n");
1.351     brouard  10000:        /* for(j=1;j<=cptcoveff;j++)  */
                   10001:        for(j=1;j<=cptcovs;j++) 
                   10002:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  10003:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  10004:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  10005:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  10006:        
                   10007:        for(j=1; j<=nlstate+ndeath;j++) {
                   10008:          ppij=0.;
                   10009:          for(i=1; i<=nlstate;i++) {
1.278     brouard  10010:            if (mobilav>=1)
                   10011:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10012:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10013:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10014:            }
1.268     brouard  10015:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10016:          } /* end i */
                   10017:          fprintf(ficresf," %.3f", ppij);
                   10018:        }/* end j */
1.227     brouard  10019:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10020:       } /* end agec */
1.266     brouard  10021:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10022:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  10023:     } /* end yearp */
                   10024:   } /* end  k */
1.219     brouard  10025:        
1.126     brouard  10026:   fclose(ficresf);
1.215     brouard  10027:   printf("End of Computing forecasting \n");
                   10028:   fprintf(ficlog,"End of Computing forecasting\n");
                   10029: 
1.126     brouard  10030: }
                   10031: 
1.269     brouard  10032: /************** Back Forecasting ******************/
1.296     brouard  10033:  /* 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){ */
                   10034:  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){
                   10035:   /* back1, year, month, day of starting backprojection
1.267     brouard  10036:      agemin, agemax range of age
                   10037:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  10038:      anback2 year of end of backprojection (same day and month as back1).
                   10039:      prevacurrent and prev are prevalences.
1.267     brouard  10040:   */
                   10041:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10042:   double agec; /* generic age */
1.302     brouard  10043:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  10044:   double *popeffectif,*popcount;
                   10045:   double ***p3mat;
                   10046:   /* double ***mobaverage; */
                   10047:   char fileresfb[FILENAMELENGTH];
                   10048:  
1.268     brouard  10049:   agelim=AGEINF;
1.267     brouard  10050:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10051:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10052:      We still use firstpass and lastpass as another selection.
                   10053:   */
                   10054:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10055:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10056: 
                   10057:   /*Do we need to compute prevalence again?*/
                   10058: 
                   10059:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10060:   
                   10061:   strcpy(fileresfb,"FB_");
                   10062:   strcat(fileresfb,fileresu);
                   10063:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10064:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10065:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10066:   }
                   10067:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10068:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10069:   
                   10070:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10071:   
                   10072:    
                   10073:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10074:   if (stepm<=12) stepsize=1;
                   10075:   if(estepm < stepm){
                   10076:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10077:   }
1.270     brouard  10078:   else{
                   10079:     hstepm=estepm;   
                   10080:   }
                   10081:   if(estepm >= stepm){ /* Yes every two year */
                   10082:     stepsize=2;
                   10083:   }
1.267     brouard  10084:   
                   10085:   hstepm=hstepm/stepm;
1.296     brouard  10086:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10087:   /*                              fractional in yp1 *\/ */
                   10088:   /* aintmean=yp; */
                   10089:   /* yp2=modf((yp1*12),&yp); */
                   10090:   /* mintmean=yp; */
                   10091:   /* yp1=modf((yp2*30.5),&yp); */
                   10092:   /* jintmean=yp; */
                   10093:   /* if(jintmean==0) jintmean=1; */
                   10094:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  10095:   
1.351     brouard  10096:   /* i1=pow(2,cptcoveff); */
                   10097:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  10098:   
1.296     brouard  10099:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10100:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  10101:   
                   10102:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10103:   
1.351     brouard  10104:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10105:     k=TKresult[nres];
                   10106:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10107:   /* for(k=1; k<=i1;k++){ */
                   10108:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10109:   /*     continue; */
                   10110:   /*   if(invalidvarcomb[k]){ */
                   10111:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10112:   /*     continue; */
                   10113:   /*   } */
1.268     brouard  10114:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  10115:     for(j=1;j<=cptcovs;j++){
                   10116:     /* for(j=1;j<=cptcoveff;j++) { */
                   10117:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10118:     /* } */
                   10119:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  10120:     }
1.351     brouard  10121:    /*  fprintf(ficrespij,"******\n"); */
                   10122:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10123:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10124:    /*  } */
1.267     brouard  10125:     fprintf(ficresfb," yearbproj age");
                   10126:     for(j=1; j<=nlstate+ndeath;j++){
                   10127:       for(i=1; i<=nlstate;i++)
1.268     brouard  10128:        fprintf(ficresfb," b%d%d",i,j);
                   10129:       fprintf(ficresfb," b.%d",j);
1.267     brouard  10130:     }
1.296     brouard  10131:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  10132:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10133:       fprintf(ficresfb,"\n");
1.296     brouard  10134:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  10135:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  10136:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10137:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  10138:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  10139:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  10140:        nhstepm = nhstepm/hstepm;
                   10141:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10142:        oldm=oldms;savm=savms;
1.268     brouard  10143:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  10144:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  10145:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  10146:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10147:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10148:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  10149:        for (h=0; h<=nhstepm; h++){
1.268     brouard  10150:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10151:            break;
                   10152:          }
                   10153:        }
                   10154:        fprintf(ficresfb,"\n");
1.351     brouard  10155:        /* for(j=1;j<=cptcoveff;j++) */
                   10156:        for(j=1;j<=cptcovs;j++)
                   10157:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10158:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  10159:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  10160:        for(i=1; i<=nlstate+ndeath;i++) {
                   10161:          ppij=0.;ppi=0.;
                   10162:          for(j=1; j<=nlstate;j++) {
                   10163:            /* if (mobilav==1) */
1.269     brouard  10164:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10165:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10166:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10167:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  10168:              /* else { */
                   10169:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10170:              /* } */
1.268     brouard  10171:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10172:          } /* end j */
                   10173:          if(ppi <0.99){
                   10174:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10175:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10176:          }
                   10177:          fprintf(ficresfb," %.3f", ppij);
                   10178:        }/* end j */
1.267     brouard  10179:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10180:       } /* end agec */
                   10181:     } /* end yearp */
                   10182:   } /* end k */
1.217     brouard  10183:   
1.267     brouard  10184:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  10185:   
1.267     brouard  10186:   fclose(ficresfb);
                   10187:   printf("End of Computing Back forecasting \n");
                   10188:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  10189:        
1.267     brouard  10190: }
1.217     brouard  10191: 
1.269     brouard  10192: /* Variance of prevalence limit: varprlim */
                   10193:  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  10194:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  10195:  
                   10196:    char fileresvpl[FILENAMELENGTH];  
                   10197:    FILE *ficresvpl;
                   10198:    double **oldm, **savm;
                   10199:    double **varpl; /* Variances of prevalence limits by age */   
                   10200:    int i1, k, nres, j ;
                   10201:    
                   10202:     strcpy(fileresvpl,"VPL_");
                   10203:     strcat(fileresvpl,fileresu);
                   10204:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  10205:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  10206:       exit(0);
                   10207:     }
1.288     brouard  10208:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10209:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  10210:     
                   10211:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10212:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10213:     
                   10214:     i1=pow(2,cptcoveff);
                   10215:     if (cptcovn < 1){i1=1;}
                   10216: 
1.337     brouard  10217:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10218:        k=TKresult[nres];
1.338     brouard  10219:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10220:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  10221:       if(i1 != 1 && TKresult[nres]!= k)
                   10222:        continue;
                   10223:       fprintf(ficresvpl,"\n#****** ");
                   10224:       printf("\n#****** ");
                   10225:       fprintf(ficlog,"\n#****** ");
1.337     brouard  10226:       for(j=1;j<=cptcovs;j++) {
                   10227:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10228:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10229:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10230:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10231:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  10232:       }
1.337     brouard  10233:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10234:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10235:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10236:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10237:       /* }      */
1.269     brouard  10238:       fprintf(ficresvpl,"******\n");
                   10239:       printf("******\n");
                   10240:       fprintf(ficlog,"******\n");
                   10241:       
                   10242:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10243:       oldm=oldms;savm=savms;
                   10244:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10245:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10246:       /*}*/
                   10247:     }
                   10248:     
                   10249:     fclose(ficresvpl);
1.288     brouard  10250:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10251:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  10252: 
                   10253:  }
                   10254: /* Variance of back prevalence: varbprlim */
                   10255:  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){
                   10256:       /*------- Variance of back (stable) prevalence------*/
                   10257: 
                   10258:    char fileresvbl[FILENAMELENGTH];  
                   10259:    FILE  *ficresvbl;
                   10260: 
                   10261:    double **oldm, **savm;
                   10262:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10263:    int i1, k, nres, j ;
                   10264: 
                   10265:    strcpy(fileresvbl,"VBL_");
                   10266:    strcat(fileresvbl,fileresu);
                   10267:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10268:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10269:      exit(0);
                   10270:    }
                   10271:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10272:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10273:    
                   10274:    
                   10275:    i1=pow(2,cptcoveff);
                   10276:    if (cptcovn < 1){i1=1;}
                   10277:    
1.337     brouard  10278:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10279:      k=TKresult[nres];
1.338     brouard  10280:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  10281:     /* for(k=1; k<=i1;k++){ */
                   10282:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10283:     /*          continue; */
1.269     brouard  10284:        fprintf(ficresvbl,"\n#****** ");
                   10285:        printf("\n#****** ");
                   10286:        fprintf(ficlog,"\n#****** ");
1.337     brouard  10287:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  10288:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10289:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10290:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  10291:        /* for(j=1;j<=cptcoveff;j++) { */
                   10292:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10293:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10294:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10295:        /* } */
                   10296:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10297:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10298:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10299:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  10300:        }
                   10301:        fprintf(ficresvbl,"******\n");
                   10302:        printf("******\n");
                   10303:        fprintf(ficlog,"******\n");
                   10304:        
                   10305:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10306:        oldm=oldms;savm=savms;
                   10307:        
                   10308:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10309:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10310:        /*}*/
                   10311:      }
                   10312:    
                   10313:    fclose(ficresvbl);
                   10314:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10315:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10316: 
                   10317:  } /* End of varbprlim */
                   10318: 
1.126     brouard  10319: /************** Forecasting *****not tested NB*************/
1.227     brouard  10320: /* 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  10321:   
1.227     brouard  10322: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10323: /*   int *popage; */
                   10324: /*   double calagedatem, agelim, kk1, kk2; */
                   10325: /*   double *popeffectif,*popcount; */
                   10326: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10327: /*   /\* double ***mobaverage; *\/ */
                   10328: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10329: 
1.227     brouard  10330: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10331: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10332: /*   agelim=AGESUP; */
                   10333: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10334:   
1.227     brouard  10335: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10336:   
                   10337:   
1.227     brouard  10338: /*   strcpy(filerespop,"POP_");  */
                   10339: /*   strcat(filerespop,fileresu); */
                   10340: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10341: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10342: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10343: /*   } */
                   10344: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10345: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10346: 
1.227     brouard  10347: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10348: 
1.227     brouard  10349: /*   /\* if (mobilav!=0) { *\/ */
                   10350: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10351: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10352: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10353: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10354: /*   /\*   } *\/ */
                   10355: /*   /\* } *\/ */
1.126     brouard  10356: 
1.227     brouard  10357: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10358: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10359:   
1.227     brouard  10360: /*   agelim=AGESUP; */
1.126     brouard  10361:   
1.227     brouard  10362: /*   hstepm=1; */
                   10363: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10364:        
1.227     brouard  10365: /*   if (popforecast==1) { */
                   10366: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10367: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10368: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10369: /*     }  */
                   10370: /*     popage=ivector(0,AGESUP); */
                   10371: /*     popeffectif=vector(0,AGESUP); */
                   10372: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10373:     
1.227     brouard  10374: /*     i=1;    */
                   10375: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10376:     
1.227     brouard  10377: /*     imx=i; */
                   10378: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10379: /*   } */
1.218     brouard  10380:   
1.227     brouard  10381: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10382: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10383: /*       k=k+1; */
                   10384: /*       fprintf(ficrespop,"\n#******"); */
                   10385: /*       for(j=1;j<=cptcoveff;j++) { */
                   10386: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10387: /*       } */
                   10388: /*       fprintf(ficrespop,"******\n"); */
                   10389: /*       fprintf(ficrespop,"# Age"); */
                   10390: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10391: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10392:       
1.227     brouard  10393: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10394: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10395:        
1.227     brouard  10396: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10397: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10398: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10399:          
1.227     brouard  10400: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10401: /*       oldm=oldms;savm=savms; */
                   10402: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10403:          
1.227     brouard  10404: /*       for (h=0; h<=nhstepm; h++){ */
                   10405: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10406: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10407: /*         }  */
                   10408: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10409: /*           kk1=0.;kk2=0; */
                   10410: /*           for(i=1; i<=nlstate;i++) {               */
                   10411: /*             if (mobilav==1)  */
                   10412: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10413: /*             else { */
                   10414: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10415: /*             } */
                   10416: /*           } */
                   10417: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10418: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10419: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10420: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10421: /*           } */
                   10422: /*         } */
                   10423: /*         for(i=1; i<=nlstate;i++){ */
                   10424: /*           kk1=0.; */
                   10425: /*           for(j=1; j<=nlstate;j++){ */
                   10426: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10427: /*           } */
                   10428: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10429: /*         } */
1.218     brouard  10430:            
1.227     brouard  10431: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10432: /*           for(j=1; j<=nlstate;j++)  */
                   10433: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10434: /*       } */
                   10435: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10436: /*     } */
                   10437: /*       } */
1.218     brouard  10438:       
1.227     brouard  10439: /*       /\******\/ */
1.218     brouard  10440:       
1.227     brouard  10441: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10442: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10443: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10444: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10445: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10446:          
1.227     brouard  10447: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10448: /*       oldm=oldms;savm=savms; */
                   10449: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10450: /*       for (h=0; h<=nhstepm; h++){ */
                   10451: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10452: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10453: /*         }  */
                   10454: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10455: /*           kk1=0.;kk2=0; */
                   10456: /*           for(i=1; i<=nlstate;i++) {               */
                   10457: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10458: /*           } */
                   10459: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10460: /*         } */
                   10461: /*       } */
                   10462: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10463: /*     } */
                   10464: /*       } */
                   10465: /*     }  */
                   10466: /*   } */
1.218     brouard  10467:   
1.227     brouard  10468: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10469:   
1.227     brouard  10470: /*   if (popforecast==1) { */
                   10471: /*     free_ivector(popage,0,AGESUP); */
                   10472: /*     free_vector(popeffectif,0,AGESUP); */
                   10473: /*     free_vector(popcount,0,AGESUP); */
                   10474: /*   } */
                   10475: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10476: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10477: /*   fclose(ficrespop); */
                   10478: /* } /\* End of popforecast *\/ */
1.218     brouard  10479:  
1.126     brouard  10480: int fileappend(FILE *fichier, char *optionfich)
                   10481: {
                   10482:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10483:     printf("Problem with file: %s\n", optionfich);
                   10484:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10485:     return (0);
                   10486:   }
                   10487:   fflush(fichier);
                   10488:   return (1);
                   10489: }
                   10490: 
                   10491: 
                   10492: /**************** function prwizard **********************/
                   10493: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10494: {
                   10495: 
                   10496:   /* Wizard to print covariance matrix template */
                   10497: 
1.164     brouard  10498:   char ca[32], cb[32];
                   10499:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10500:   int numlinepar;
                   10501: 
                   10502:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10503:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10504:   for(i=1; i <=nlstate; i++){
                   10505:     jj=0;
                   10506:     for(j=1; j <=nlstate+ndeath; j++){
                   10507:       if(j==i) continue;
                   10508:       jj++;
                   10509:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10510:       printf("%1d%1d",i,j);
                   10511:       fprintf(ficparo,"%1d%1d",i,j);
                   10512:       for(k=1; k<=ncovmodel;k++){
                   10513:        /*        printf(" %lf",param[i][j][k]); */
                   10514:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10515:        printf(" 0.");
                   10516:        fprintf(ficparo," 0.");
                   10517:       }
                   10518:       printf("\n");
                   10519:       fprintf(ficparo,"\n");
                   10520:     }
                   10521:   }
                   10522:   printf("# Scales (for hessian or gradient estimation)\n");
                   10523:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10524:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10525:   for(i=1; i <=nlstate; i++){
                   10526:     jj=0;
                   10527:     for(j=1; j <=nlstate+ndeath; j++){
                   10528:       if(j==i) continue;
                   10529:       jj++;
                   10530:       fprintf(ficparo,"%1d%1d",i,j);
                   10531:       printf("%1d%1d",i,j);
                   10532:       fflush(stdout);
                   10533:       for(k=1; k<=ncovmodel;k++){
                   10534:        /*      printf(" %le",delti3[i][j][k]); */
                   10535:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10536:        printf(" 0.");
                   10537:        fprintf(ficparo," 0.");
                   10538:       }
                   10539:       numlinepar++;
                   10540:       printf("\n");
                   10541:       fprintf(ficparo,"\n");
                   10542:     }
                   10543:   }
                   10544:   printf("# Covariance matrix\n");
                   10545: /* # 121 Var(a12)\n\ */
                   10546: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10547: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10548: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10549: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10550: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10551: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10552: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10553:   fflush(stdout);
                   10554:   fprintf(ficparo,"# Covariance matrix\n");
                   10555:   /* # 121 Var(a12)\n\ */
                   10556:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10557:   /* #   ...\n\ */
                   10558:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10559:   
                   10560:   for(itimes=1;itimes<=2;itimes++){
                   10561:     jj=0;
                   10562:     for(i=1; i <=nlstate; i++){
                   10563:       for(j=1; j <=nlstate+ndeath; j++){
                   10564:        if(j==i) continue;
                   10565:        for(k=1; k<=ncovmodel;k++){
                   10566:          jj++;
                   10567:          ca[0]= k+'a'-1;ca[1]='\0';
                   10568:          if(itimes==1){
                   10569:            printf("#%1d%1d%d",i,j,k);
                   10570:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10571:          }else{
                   10572:            printf("%1d%1d%d",i,j,k);
                   10573:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10574:            /*  printf(" %.5le",matcov[i][j]); */
                   10575:          }
                   10576:          ll=0;
                   10577:          for(li=1;li <=nlstate; li++){
                   10578:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10579:              if(lj==li) continue;
                   10580:              for(lk=1;lk<=ncovmodel;lk++){
                   10581:                ll++;
                   10582:                if(ll<=jj){
                   10583:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10584:                  if(ll<jj){
                   10585:                    if(itimes==1){
                   10586:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10587:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10588:                    }else{
                   10589:                      printf(" 0.");
                   10590:                      fprintf(ficparo," 0.");
                   10591:                    }
                   10592:                  }else{
                   10593:                    if(itimes==1){
                   10594:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10595:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10596:                    }else{
                   10597:                      printf(" 0.");
                   10598:                      fprintf(ficparo," 0.");
                   10599:                    }
                   10600:                  }
                   10601:                }
                   10602:              } /* end lk */
                   10603:            } /* end lj */
                   10604:          } /* end li */
                   10605:          printf("\n");
                   10606:          fprintf(ficparo,"\n");
                   10607:          numlinepar++;
                   10608:        } /* end k*/
                   10609:       } /*end j */
                   10610:     } /* end i */
                   10611:   } /* end itimes */
                   10612: 
                   10613: } /* end of prwizard */
                   10614: /******************* Gompertz Likelihood ******************************/
                   10615: double gompertz(double x[])
                   10616: { 
1.302     brouard  10617:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10618:   int i,n=0; /* n is the size of the sample */
                   10619: 
1.220     brouard  10620:   for (i=1;i<=imx ; i++) {
1.126     brouard  10621:     sump=sump+weight[i];
                   10622:     /*    sump=sump+1;*/
                   10623:     num=num+1;
                   10624:   }
1.302     brouard  10625:   L=0.0;
                   10626:   /* agegomp=AGEGOMP; */
1.126     brouard  10627:   /* for (i=0; i<=imx; i++) 
                   10628:      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]);*/
                   10629: 
1.302     brouard  10630:   for (i=1;i<=imx ; i++) {
                   10631:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10632:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10633:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10634:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10635:      * +
                   10636:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10637:      */
                   10638:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10639:        if (cens[i] == 1){
                   10640:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10641:        } else if (cens[i] == 0){
1.126     brouard  10642:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10643:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10644:       } else
                   10645:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10646:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10647:        L=L+A*weight[i];
1.126     brouard  10648:        /*      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  10649:      }
                   10650:   }
1.126     brouard  10651: 
1.302     brouard  10652:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10653:  
                   10654:   return -2*L*num/sump;
                   10655: }
                   10656: 
1.136     brouard  10657: #ifdef GSL
                   10658: /******************* Gompertz_f Likelihood ******************************/
                   10659: double gompertz_f(const gsl_vector *v, void *params)
                   10660: { 
1.302     brouard  10661:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10662:   double *x= (double *) v->data;
                   10663:   int i,n=0; /* n is the size of the sample */
                   10664: 
                   10665:   for (i=0;i<=imx-1 ; i++) {
                   10666:     sump=sump+weight[i];
                   10667:     /*    sump=sump+1;*/
                   10668:     num=num+1;
                   10669:   }
                   10670:  
                   10671:  
                   10672:   /* for (i=0; i<=imx; i++) 
                   10673:      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]);*/
                   10674:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10675:   for (i=1;i<=imx ; i++)
                   10676:     {
                   10677:       if (cens[i] == 1 && wav[i]>1)
                   10678:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10679:       
                   10680:       if (cens[i] == 0 && wav[i]>1)
                   10681:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10682:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10683:       
                   10684:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10685:       if (wav[i] > 1 ) { /* ??? */
                   10686:        LL=LL+A*weight[i];
                   10687:        /*      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]);*/
                   10688:       }
                   10689:     }
                   10690: 
                   10691:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10692:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10693:  
                   10694:   return -2*LL*num/sump;
                   10695: }
                   10696: #endif
                   10697: 
1.126     brouard  10698: /******************* Printing html file ***********/
1.201     brouard  10699: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10700:                  int lastpass, int stepm, int weightopt, char model[],\
                   10701:                  int imx,  double p[],double **matcov,double agemortsup){
                   10702:   int i,k;
                   10703: 
                   10704:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10705:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10706:   for (i=1;i<=2;i++) 
                   10707:     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  10708:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10709:   fprintf(fichtm,"</ul>");
                   10710: 
                   10711: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10712: 
                   10713:  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>");
                   10714: 
                   10715:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10716:    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]);
                   10717: 
                   10718:  
                   10719:   fflush(fichtm);
                   10720: }
                   10721: 
                   10722: /******************* Gnuplot file **************/
1.201     brouard  10723: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10724: 
                   10725:   char dirfileres[132],optfileres[132];
1.164     brouard  10726: 
1.126     brouard  10727:   int ng;
                   10728: 
                   10729: 
                   10730:   /*#ifdef windows */
                   10731:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10732:     /*#endif */
                   10733: 
                   10734: 
                   10735:   strcpy(dirfileres,optionfilefiname);
                   10736:   strcpy(optfileres,"vpl");
1.199     brouard  10737:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10738:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10739:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10740:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10741:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10742: 
                   10743: } 
                   10744: 
1.136     brouard  10745: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10746: {
1.126     brouard  10747: 
1.136     brouard  10748:   /*-------- data file ----------*/
                   10749:   FILE *fic;
                   10750:   char dummy[]="                         ";
1.240     brouard  10751:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10752:   int lstra;
1.136     brouard  10753:   int linei, month, year,iout;
1.302     brouard  10754:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10755:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10756:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10757:   char *stratrunc;
1.223     brouard  10758: 
1.349     brouard  10759:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   10760:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  10761:   
                   10762:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10763:   
1.136     brouard  10764:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10765:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10766:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10767:   }
1.126     brouard  10768: 
1.302     brouard  10769:     /* Is it a BOM UTF-8 Windows file? */
                   10770:   /* First data line */
                   10771:   linei=0;
                   10772:   while(fgets(line, MAXLINE, fic)) {
                   10773:     noffset=0;
                   10774:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10775:     {
                   10776:       noffset=noffset+3;
                   10777:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10778:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10779:       fflush(ficlog); return 1;
                   10780:     }
                   10781:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10782:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10783:     {
                   10784:       noffset=noffset+2;
1.304     brouard  10785:       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);
                   10786:       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  10787:       fflush(ficlog); return 1;
                   10788:     }
                   10789:     else if( line[0] == 0 && line[1] == 0)
                   10790:     {
                   10791:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10792:        noffset=noffset+4;
1.304     brouard  10793:        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);
                   10794:        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  10795:        fflush(ficlog); return 1;
                   10796:       }
                   10797:     } else{
                   10798:       ;/*printf(" Not a BOM file\n");*/
                   10799:     }
                   10800:         /* If line starts with a # it is a comment */
                   10801:     if (line[noffset] == '#') {
                   10802:       linei=linei+1;
                   10803:       break;
                   10804:     }else{
                   10805:       break;
                   10806:     }
                   10807:   }
                   10808:   fclose(fic);
                   10809:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10810:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10811:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10812:   }
                   10813:   /* Not a Bom file */
                   10814:   
1.136     brouard  10815:   i=1;
                   10816:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10817:     linei=linei+1;
                   10818:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10819:       if(line[j] == '\t')
                   10820:        line[j] = ' ';
                   10821:     }
                   10822:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10823:       ;
                   10824:     };
                   10825:     line[j+1]=0;  /* Trims blanks at end of line */
                   10826:     if(line[0]=='#'){
                   10827:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10828:       printf("Comment line\n%s\n",line);
                   10829:       continue;
                   10830:     }
                   10831:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10832:     strcpy(line, linetmp);
1.223     brouard  10833:     
                   10834:     /* Loops on waves */
                   10835:     for (j=maxwav;j>=1;j--){
                   10836:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10837:        cutv(stra, strb, line, ' '); 
                   10838:        if(strb[0]=='.') { /* Missing value */
                   10839:          lval=-1;
                   10840:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10841:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10842:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10843:            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);
                   10844:            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);
                   10845:            return 1;
                   10846:          }
                   10847:        }else{
                   10848:          errno=0;
                   10849:          /* what_kind_of_number(strb); */
                   10850:          dval=strtod(strb,&endptr); 
                   10851:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10852:          /* if(strb != endptr && *endptr == '\0') */
                   10853:          /*    dval=dlval; */
                   10854:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10855:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10856:            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);
                   10857:            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);
                   10858:            return 1;
                   10859:          }
                   10860:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10861:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10862:        }
                   10863:        strcpy(line,stra);
1.223     brouard  10864:       }/* end loop ntqv */
1.225     brouard  10865:       
1.223     brouard  10866:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10867:        cutv(stra, strb, line, ' '); 
                   10868:        if(strb[0]=='.') { /* Missing value */
                   10869:          lval=-1;
                   10870:        }else{
                   10871:          errno=0;
                   10872:          lval=strtol(strb,&endptr,10); 
                   10873:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10874:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10875:            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);
                   10876:            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);
                   10877:            return 1;
                   10878:          }
                   10879:        }
                   10880:        if(lval <-1 || lval >1){
                   10881:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10882:  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  10883:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10884:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10885:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10886:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10887:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10888:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10889:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10890:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10891:  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  10892:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10893:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10894:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10895:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10896:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10897:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10898:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10899:          return 1;
                   10900:        }
1.341     brouard  10901:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10902:        strcpy(line,stra);
1.223     brouard  10903:       }/* end loop ntv */
1.225     brouard  10904:       
1.223     brouard  10905:       /* Statuses  at wave */
1.137     brouard  10906:       cutv(stra, strb, line, ' '); 
1.223     brouard  10907:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10908:        lval=-1;
1.136     brouard  10909:       }else{
1.238     brouard  10910:        errno=0;
                   10911:        lval=strtol(strb,&endptr,10); 
                   10912:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  10913:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   10914:          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);
                   10915:          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);
                   10916:          return 1;
                   10917:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  10918:          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);
                   10919:          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  10920:          return 1;
                   10921:        }
1.136     brouard  10922:       }
1.225     brouard  10923:       
1.136     brouard  10924:       s[j][i]=lval;
1.225     brouard  10925:       
1.223     brouard  10926:       /* Date of Interview */
1.136     brouard  10927:       strcpy(line,stra);
                   10928:       cutv(stra, strb,line,' ');
1.169     brouard  10929:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10930:       }
1.169     brouard  10931:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10932:        month=99;
                   10933:        year=9999;
1.136     brouard  10934:       }else{
1.225     brouard  10935:        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);
                   10936:        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);
                   10937:        return 1;
1.136     brouard  10938:       }
                   10939:       anint[j][i]= (double) year; 
1.302     brouard  10940:       mint[j][i]= (double)month;
                   10941:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10942:       /*       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]); */
                   10943:       /*       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]); */
                   10944:       /* } */
1.136     brouard  10945:       strcpy(line,stra);
1.223     brouard  10946:     } /* End loop on waves */
1.225     brouard  10947:     
1.223     brouard  10948:     /* Date of death */
1.136     brouard  10949:     cutv(stra, strb,line,' '); 
1.169     brouard  10950:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10951:     }
1.169     brouard  10952:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10953:       month=99;
                   10954:       year=9999;
                   10955:     }else{
1.141     brouard  10956:       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  10957:       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);
                   10958:       return 1;
1.136     brouard  10959:     }
                   10960:     andc[i]=(double) year; 
                   10961:     moisdc[i]=(double) month; 
                   10962:     strcpy(line,stra);
                   10963:     
1.223     brouard  10964:     /* Date of birth */
1.136     brouard  10965:     cutv(stra, strb,line,' '); 
1.169     brouard  10966:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10967:     }
1.169     brouard  10968:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10969:       month=99;
                   10970:       year=9999;
                   10971:     }else{
1.141     brouard  10972:       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);
                   10973:       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  10974:       return 1;
1.136     brouard  10975:     }
                   10976:     if (year==9999) {
1.141     brouard  10977:       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);
                   10978:       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  10979:       return 1;
                   10980:       
1.136     brouard  10981:     }
                   10982:     annais[i]=(double)(year);
1.302     brouard  10983:     moisnais[i]=(double)(month);
                   10984:     for (j=1;j<=maxwav;j++){
                   10985:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10986:        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]);
                   10987:        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]);
                   10988:       }
                   10989:     }
                   10990: 
1.136     brouard  10991:     strcpy(line,stra);
1.225     brouard  10992:     
1.223     brouard  10993:     /* Sample weight */
1.136     brouard  10994:     cutv(stra, strb,line,' '); 
                   10995:     errno=0;
                   10996:     dval=strtod(strb,&endptr); 
                   10997:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10998:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10999:       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  11000:       fflush(ficlog);
                   11001:       return 1;
                   11002:     }
                   11003:     weight[i]=dval; 
                   11004:     strcpy(line,stra);
1.225     brouard  11005:     
1.223     brouard  11006:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11007:       cutv(stra, strb, line, ' '); 
                   11008:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  11009:        lval=-1;
1.311     brouard  11010:        coqvar[iv][i]=NAN; 
                   11011:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11012:       }else{
1.225     brouard  11013:        errno=0;
                   11014:        /* what_kind_of_number(strb); */
                   11015:        dval=strtod(strb,&endptr);
                   11016:        /* if(strb != endptr && *endptr == '\0') */
                   11017:        /*   dval=dlval; */
                   11018:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11019:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11020:          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);
                   11021:          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);
                   11022:          return 1;
                   11023:        }
                   11024:        coqvar[iv][i]=dval; 
1.226     brouard  11025:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  11026:       }
                   11027:       strcpy(line,stra);
                   11028:     }/* end loop nqv */
1.136     brouard  11029:     
1.223     brouard  11030:     /* Covariate values */
1.136     brouard  11031:     for (j=ncovcol;j>=1;j--){
                   11032:       cutv(stra, strb,line,' '); 
1.223     brouard  11033:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  11034:        lval=-1;
1.136     brouard  11035:       }else{
1.225     brouard  11036:        errno=0;
                   11037:        lval=strtol(strb,&endptr,10); 
                   11038:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11039:          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);
                   11040:          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);
                   11041:          return 1;
                   11042:        }
1.136     brouard  11043:       }
                   11044:       if(lval <-1 || lval >1){
1.225     brouard  11045:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11046:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11047:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11048:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11049:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11050:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11051:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11052:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11053:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  11054:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  11055:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11056:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  11057:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11058:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11059:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  11060:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  11061:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  11062:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  11063:        return 1;
1.136     brouard  11064:       }
                   11065:       covar[j][i]=(double)(lval);
                   11066:       strcpy(line,stra);
                   11067:     }  
                   11068:     lstra=strlen(stra);
1.225     brouard  11069:     
1.136     brouard  11070:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11071:       stratrunc = &(stra[lstra-9]);
                   11072:       num[i]=atol(stratrunc);
                   11073:     }
                   11074:     else
                   11075:       num[i]=atol(stra);
                   11076:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11077:       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;}*/
                   11078:     
                   11079:     i=i+1;
                   11080:   } /* End loop reading  data */
1.225     brouard  11081:   
1.136     brouard  11082:   *imax=i-1; /* Number of individuals */
                   11083:   fclose(fic);
1.225     brouard  11084:   
1.136     brouard  11085:   return (0);
1.164     brouard  11086:   /* endread: */
1.225     brouard  11087:   printf("Exiting readdata: ");
                   11088:   fclose(fic);
                   11089:   return (1);
1.223     brouard  11090: }
1.126     brouard  11091: 
1.234     brouard  11092: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  11093:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  11094:   while (*p2 == ' ')
1.234     brouard  11095:     p2++; 
                   11096:   /* while ((*p1++ = *p2++) !=0) */
                   11097:   /*   ; */
                   11098:   /* do */
                   11099:   /*   while (*p2 == ' ') */
                   11100:   /*     p2++; */
                   11101:   /* while (*p1++ == *p2++); */
                   11102:   *stri=p2; 
1.145     brouard  11103: }
                   11104: 
1.330     brouard  11105: int decoderesult( char resultline[], int nres)
1.230     brouard  11106: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11107: {
1.235     brouard  11108:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  11109:   char resultsav[MAXLINE];
1.330     brouard  11110:   /* int resultmodel[MAXLINE]; */
1.334     brouard  11111:   /* int modelresult[MAXLINE]; */
1.230     brouard  11112:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11113: 
1.234     brouard  11114:   removefirstspace(&resultline);
1.332     brouard  11115:   printf("decoderesult:%s\n",resultline);
1.230     brouard  11116: 
1.332     brouard  11117:   strcpy(resultsav,resultline);
1.342     brouard  11118:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  11119:   if (strlen(resultsav) >1){
1.334     brouard  11120:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  11121:   }
1.253     brouard  11122:   if(j == 0){ /* Resultline but no = */
                   11123:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11124:     return (0);
                   11125:   }
1.234     brouard  11126:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  11127:     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);
                   11128:     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  11129:     /* return 1;*/
1.234     brouard  11130:   }
1.334     brouard  11131:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  11132:     if(nbocc(resultsav,'=') >1){
1.318     brouard  11133:       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  11134:       /* 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  11135:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  11136:       /* If a blank, then strc="V4=" and strd='\0' */
                   11137:       if(strc[0]=='\0'){
                   11138:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11139:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11140:        return 1;
                   11141:       }
1.234     brouard  11142:     }else
                   11143:       cutl(strc,strd,resultsav,'=');
1.318     brouard  11144:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  11145:     
1.230     brouard  11146:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  11147:     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  11148:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11149:     /* cptcovsel++;     */
                   11150:     if (nbocc(stra,'=') >0)
                   11151:       strcpy(resultsav,stra); /* and analyzes it */
                   11152:   }
1.235     brouard  11153:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11154:   /* 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  11155:   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  11156:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11157:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  11158:       match=0;
1.318     brouard  11159:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11160:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11161:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  11162:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  11163:          break;
                   11164:        }
                   11165:       }
                   11166:       if(match == 0){
1.338     brouard  11167:        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]);
                   11168:        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  11169:        return 1;
1.234     brouard  11170:       }
1.332     brouard  11171:     }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*/
                   11172:       /* We feed resultmodel[k1]=k2; */
                   11173:       match=0;
                   11174:       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 */
                   11175:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  11176:          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  11177:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  11178:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  11179:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11180:          break;
                   11181:        }
                   11182:       }
                   11183:       if(match == 0){
1.338     brouard  11184:        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]);
                   11185:        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  11186:       return 1;
                   11187:       }
1.349     brouard  11188:     }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  11189:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11190:       match=0;
1.342     brouard  11191:       /* 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  11192:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11193:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11194:          /* modelresult[k2]=k1; */
1.342     brouard  11195:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  11196:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11197:        }
                   11198:       }
                   11199:       if(match == 0){
1.349     brouard  11200:        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);
                   11201:        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  11202:        return 1;
                   11203:       }
                   11204:       match=0;
                   11205:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11206:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11207:          /* modelresult[k2]=k1;*/
1.342     brouard  11208:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  11209:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11210:          break;
                   11211:        }
                   11212:       }
                   11213:       if(match == 0){
1.349     brouard  11214:        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);
                   11215:        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  11216:        return 1;
                   11217:       }
                   11218:     }/* End of testing */
1.333     brouard  11219:   }/* End loop cptcovt */
1.235     brouard  11220:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  11221:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  11222:   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)
                   11223:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  11224:     match=0;
1.318     brouard  11225:     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  11226:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  11227:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  11228:          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  11229:          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  11230:          ++match;
                   11231:        }
                   11232:       }
                   11233:     }
                   11234:     if(match == 0){
1.338     brouard  11235:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11236:       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  11237:       return 1;
1.234     brouard  11238:     }else if(match > 1){
1.338     brouard  11239:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11240:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  11241:       return 1;
1.234     brouard  11242:     }
                   11243:   }
1.334     brouard  11244:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  11245:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  11246:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  11247:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11248:   /* 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*/
                   11249:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  11250:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11251:   /*    1 0 0 0 */
                   11252:   /*    2 1 0 0 */
                   11253:   /*    3 0 1 0 */ 
1.330     brouard  11254:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  11255:   /*    5 0 0 1 */
1.330     brouard  11256:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  11257:   /*    7 0 1 1 */
                   11258:   /*    8 1 1 1 */
1.237     brouard  11259:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11260:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11261:   /* V5*age V5 known which value for nres?  */
                   11262:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  11263:   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.
                   11264:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  11265:     /* k counting number of combination of single dummies in the equation model */
                   11266:     /* k4 counting single dummies in the equation model */
                   11267:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  11268:     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  11269:        /* 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  11270:       /* 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  11271:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  11272:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11273:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11274:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11275:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11276:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  11277:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  11278:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  11279:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  11280:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11281:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11282:       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  11283:       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  11284:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  11285:       /* Tinvresult[nres][4]=1 */
1.334     brouard  11286:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11287:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11288:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11289:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  11290:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  11291:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  11292:       /* 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  11293:       k4++;;
1.331     brouard  11294:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  11295:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  11296:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  11297:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  11298:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11299:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11300:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11301:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11302:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11303:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11304:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11305:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11306:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  11307:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11308:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11309:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11310:       /* 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  11311:       k4q++;;
1.350     brouard  11312:     }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"*/
                   11313:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  11314:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  11315:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11316:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11317:       /* 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]]); */
                   11318:       }else{
                   11319:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11320:        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)*/
                   11321:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11322:        precov[nres][k1]=Tvalsel[k3];
                   11323:       }
1.342     brouard  11324:       /* 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  11325:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  11326:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11327:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11328:       /* 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]]); */
                   11329:       }else{
                   11330:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11331:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11332:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11333:        precov[nres][k1]=Tvalsel[k3q];
                   11334:       }
1.342     brouard  11335:       /* 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  11336:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  11337:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11338:       /* 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  11339:     }else{
1.332     brouard  11340:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11341:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11342:     }
                   11343:   }
1.234     brouard  11344:   
1.334     brouard  11345:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11346:   return (0);
                   11347: }
1.235     brouard  11348: 
1.230     brouard  11349: int decodemodel( char model[], int lastobs)
                   11350:  /**< This routine decodes the model and returns:
1.224     brouard  11351:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11352:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11353:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11354:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11355:        * - cptcovage number of covariates with age*products =2
                   11356:        * - cptcovs number of simple covariates
1.339     brouard  11357:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11358:        * - 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  11359:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11360:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11361:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11362:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11363:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11364:        */
1.319     brouard  11365: /* 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  11366: {
1.238     brouard  11367:   int i, j, k, ks, v;
1.349     brouard  11368:   int n,m;
                   11369:   int  j1, k1, k11, k12, k2, k3, k4;
                   11370:   char modelsav[300];
                   11371:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  11372:   char *strpt;
1.349     brouard  11373:   int  **existcomb;
                   11374:   
                   11375:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11376:   for(i=1;i<=NCOVMAX;i++)
                   11377:     for(j=1;j<=NCOVMAX;j++)
                   11378:       existcomb[i][j]=0;
                   11379:     
1.145     brouard  11380:   /*removespace(model);*/
1.136     brouard  11381:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  11382:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11383:     if (strstr(model,"AGE") !=0){
1.192     brouard  11384:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11385:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11386:       return 1;
                   11387:     }
1.141     brouard  11388:     if (strstr(model,"v") !=0){
1.338     brouard  11389:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11390:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11391:       return 1;
                   11392:     }
1.187     brouard  11393:     strcpy(modelsav,model); 
                   11394:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11395:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11396:       if(strpt != model){
1.338     brouard  11397:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11398:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11399:  corresponding column of parameters.\n",model);
1.338     brouard  11400:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11401:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11402:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11403:        return 1;
1.225     brouard  11404:       }
1.187     brouard  11405:       nagesqr=1;
                   11406:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11407:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11408:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11409:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11410:       else 
1.234     brouard  11411:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11412:     }else
                   11413:       nagesqr=0;
1.349     brouard  11414:     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  11415:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11416:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  11417:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  11418:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11419:                     * cst, age and age*age 
                   11420:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11421:       /* including age products which are counted in cptcovage.
                   11422:        * but the covariates which are products must be treated 
                   11423:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  11424:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11425:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  11426:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  11427:       cptcovprodage=0;
                   11428:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  11429:       
1.187     brouard  11430:       /*   Design
                   11431:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11432:        *  <          ncovcol=8                >
                   11433:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11434:        *   k=  1    2      3       4     5       6      7        8
                   11435:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  11436:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  11437:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11438:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11439:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11440:        *  Tage[++cptcovage]=k
1.345     brouard  11441:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  11442:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11443:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11444:        *  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
                   11445:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11446:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11447:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  11448:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  11449:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11450:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  11451:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11452:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  11453:        * p Tprod[1]@2={                         6, 5}
                   11454:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11455:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11456:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11457:        *How to reorganize? Tvars(orted)
1.187     brouard  11458:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11459:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11460:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11461:        * Struct []
                   11462:        */
1.225     brouard  11463:       
1.187     brouard  11464:       /* This loop fills the array Tvar from the string 'model'.*/
                   11465:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11466:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11467:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11468:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11469:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11470:       /*       k=1 Tvar[1]=2 (from V2) */
                   11471:       /*       k=5 Tvar[5] */
                   11472:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11473:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11474:       /*       } */
1.198     brouard  11475:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11476:       /*
                   11477:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11478:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11479:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11480:       }
1.187     brouard  11481:       cptcovage=0;
1.351     brouard  11482: 
                   11483:       /* First loop in order to calculate */
                   11484:       /* for age*VN*Vm
                   11485:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   11486:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   11487:       */
                   11488:       /* Needs  FixedV[Tvardk[k][1]] */
                   11489:       /* For others:
                   11490:        * Sets  Typevar[k];
                   11491:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11492:        *       Tposprod[k]=k11;
                   11493:        *       Tprod[k11]=k;
                   11494:        *       Tvardk[k][1] =m;
                   11495:        * Needs FixedV[Tvardk[k][1]] == 0
                   11496:       */
                   11497:       
1.319     brouard  11498:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11499:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11500:                                         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" */
                   11501:        if (nbocc(modelsav,'+')==0)
                   11502:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11503:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11504:        /*scanf("%d",i);*/
1.349     brouard  11505:        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 */
                   11506:          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  */
                   11507:          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   */
                   11508:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   11509:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   11510:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   11511:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   11512:              /* We want strb=Vn*Vm */
                   11513:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   11514:                 strcpy(strb,strd);
                   11515:                 strcat(strb,"*");
                   11516:                 strcat(strb,stre);
                   11517:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   11518:                 strcpy(strb,strf);
                   11519:                 strcat(strb,"*");
                   11520:                 strcat(strb,stre);
                   11521:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   11522:               }
1.351     brouard  11523:              /* 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]]]); */
                   11524:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  11525:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   11526:              strcpy(stre,strb); /* save full b in stre */
                   11527:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11528:              strcpy(strf,strc); /* save short c in new short f */
                   11529:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11530:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11531:             }
                   11532:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11533:             /* 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 *\/ */
                   11534:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  11535:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  11536:            n=atoi(stre);
1.234     brouard  11537:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  11538:            m=atoi(strc);
                   11539:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11540:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11541:            if(existcomb[n][m] == 0){
                   11542:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11543:              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);
                   11544:              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);
                   11545:              fflush(ficlog);
                   11546:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11547:              k12++;
                   11548:              existcomb[n][m]=k1;
                   11549:              existcomb[m][n]=k1;
                   11550:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11551:              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*/
                   11552:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11553:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11554:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11555:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11556:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  11557: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  11558:              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 */
                   11559:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11560:                  /* Computes the new covariate which is a product of
                   11561:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11562:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11563:                }
                   11564:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11565:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11566:                k12++;
                   11567:                FixedV[ncovcolt+k12]=0;
                   11568:              }else{ /*End of FixedV */
                   11569:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11570:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11571:                k12++;
                   11572:                FixedV[ncovcolt+k12]=1;
                   11573:              }
                   11574:            }else{  /* k1 Vn*Vm already exists */
                   11575:              k11=existcomb[n][m];
                   11576:              Tposprod[k]=k11; /* OK */
                   11577:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11578:              Tvardk[k][1]=m;
                   11579:              Tvardk[k][2]=n;
                   11580:              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 */
                   11581:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11582:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11583:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11584:                Tvar[Tage[cptcovage]]=k1;
                   11585:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11586:                k12++;
                   11587:                FixedV[ncovcolt+k12]=0;
                   11588:              }else{ /* Already exists but time varying (and age) */
                   11589:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11590:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11591:                /* Tvar[Tage[cptcovage]]=k1; */
                   11592:                cptcovprodvage++;
                   11593:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11594:                k12++;
                   11595:                FixedV[ncovcolt+k12]=1;
                   11596:              }
                   11597:            }
                   11598:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11599:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11600:          } 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 */
                   11601:             cptcovprod++;
                   11602:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11603:               /* covar is not filled and then is empty */
                   11604:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11605:               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 */
                   11606:               Typevar[k]=1;  /* 1 for age product */
                   11607:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11608:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11609:              if( FixedV[Tvar[k]] == 0){
                   11610:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11611:              }else{
                   11612:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11613:              }
                   11614:               /*printf("stre=%s ", stre);*/
                   11615:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11616:               cutl(stre,strb,strc,'V');
                   11617:               Tvar[k]=atoi(stre);
                   11618:               Typevar[k]=1;  /* 1 for age product */
                   11619:               cptcovage++;
                   11620:               Tage[cptcovage]=k;
                   11621:              if( FixedV[Tvar[k]] == 0){
                   11622:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11623:              }else{
                   11624:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  11625:              }
1.349     brouard  11626:             }else{ /*  for product Vn*Vm */
                   11627:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11628:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11629:              n=atoi(stre);
                   11630:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11631:              m=atoi(strc);
                   11632:              k1++;
                   11633:              cptcovprodnoage++;
                   11634:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11635:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11636:                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]);
                   11637:                fflush(ficlog);
                   11638:                k11=existcomb[n][m];
                   11639:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11640:                Tposprod[k]=k11;
                   11641:                Tprod[k11]=k;
                   11642:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11643:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11644:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11645:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11646:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11647:                existcomb[n][m]=k1;
                   11648:                existcomb[m][n]=k1;
                   11649:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11650:                                                    because this model-covariate is a construction we invent a new column
                   11651:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11652:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11653:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11654:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11655:                /* Please remark that the new variables are model dependent */
                   11656:                /* If we have 4 variable but the model uses only 3, like in
                   11657:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11658:                 *  k=     1     2      3   4     5        6        7       8
                   11659:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11660:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11661:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11662:                 */
                   11663:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11664:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11665:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11666:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11667:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11668:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11669:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11670:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11671:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11672:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11673:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11674:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11675:                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 */
                   11676:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11677:                    /* Computes the new covariate which is a product of
                   11678:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11679:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11680:                  }
                   11681:                  /* TvarVV[k2]=n; */
                   11682:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11683:                  /* TvarVV[k2+1]=m; */
                   11684:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11685:                }else{ /* not FixedV */
                   11686:                  /* TvarVV[k2]=n; */
                   11687:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11688:                  /* TvarVV[k2+1]=m; */
                   11689:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11690:                }                 
                   11691:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11692:            } /*  End of product Vn*Vm */
                   11693:           } /* End of age*double product or simple product */
                   11694:        }else { /* not a product */
1.234     brouard  11695:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11696:          /*  scanf("%d",i);*/
                   11697:          cutl(strd,strc,strb,'V');
                   11698:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11699:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11700:          Tvar[k]=atoi(strd);
                   11701:          Typevar[k]=0;  /* 0 for simple covariates */
                   11702:        }
                   11703:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11704:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11705:                                  scanf("%d",i);*/
1.187     brouard  11706:       } /* end of loop + on total covariates */
1.351     brouard  11707: 
                   11708:       
1.187     brouard  11709:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11710:   } /* end if strlen(model == 0) */
1.349     brouard  11711:   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  */
                   11712: 
1.136     brouard  11713:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11714:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11715:   
1.136     brouard  11716:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11717:      printf("cptcovprod=%d ", cptcovprod);
                   11718:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11719:      scanf("%d ",i);*/
                   11720: 
                   11721: 
1.230     brouard  11722: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11723:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11724: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11725:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11726:    k =           1    2   3     4       5       6      7      8        9
                   11727:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11728:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11729:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11730:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11731:          Tmodelind[combination of covar]=k;
1.225     brouard  11732: */  
                   11733: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11734:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11735:   /* 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  11736:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11737:   printf("Model=1+age+%s\n\
1.349     brouard  11738: 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  11739: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11740: 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  11741:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  11742: 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  11743: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11744: 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  11745:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11746:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  11747: 
                   11748: 
                   11749:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   11750: 
                   11751:   
1.349     brouard  11752:   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  11753:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11754:       Fixed[k]= 0;
                   11755:       Dummy[k]= 0;
1.225     brouard  11756:       ncoveff++;
1.232     brouard  11757:       ncovf++;
1.234     brouard  11758:       nsd++;
                   11759:       modell[k].maintype= FTYPE;
                   11760:       TvarsD[nsd]=Tvar[k];
                   11761:       TvarsDind[nsd]=k;
1.330     brouard  11762:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11763:       TvarF[ncovf]=Tvar[k];
                   11764:       TvarFind[ncovf]=k;
                   11765:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11766:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11767:     /* }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  11768:     }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  11769:       Fixed[k]= 0;
                   11770:       Dummy[k]= 1;
1.230     brouard  11771:       nqfveff++;
1.234     brouard  11772:       modell[k].maintype= FTYPE;
                   11773:       modell[k].subtype= FQ;
                   11774:       nsq++;
1.334     brouard  11775:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11776:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11777:       ncovf++;
1.234     brouard  11778:       TvarF[ncovf]=Tvar[k];
                   11779:       TvarFind[ncovf]=k;
1.231     brouard  11780:       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  11781:       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  11782:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11783:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11784:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11785:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11786:       ncovvt++;
                   11787:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11788:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11789: 
1.227     brouard  11790:       Fixed[k]= 1;
                   11791:       Dummy[k]= 0;
1.225     brouard  11792:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11793:       modell[k].maintype= VTYPE;
                   11794:       modell[k].subtype= VD;
                   11795:       nsd++;
                   11796:       TvarsD[nsd]=Tvar[k];
                   11797:       TvarsDind[nsd]=k;
1.330     brouard  11798:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11799:       ncovv++; /* Only simple time varying variables */
                   11800:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11801:       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  11802:       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 */
                   11803:       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  11804:       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);
                   11805:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11806:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11807:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11808:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11809:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11810:       ncovvt++;
                   11811:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11812:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11813:       
1.234     brouard  11814:       Fixed[k]= 1;
                   11815:       Dummy[k]= 1;
                   11816:       nqtveff++;
                   11817:       modell[k].maintype= VTYPE;
                   11818:       modell[k].subtype= VQ;
                   11819:       ncovv++; /* Only simple time varying variables */
                   11820:       nsq++;
1.334     brouard  11821:       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) */
                   11822:       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  11823:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11824:       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  11825:       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 */
                   11826:       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  11827:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11828:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  11829:       /* 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  11830:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11831:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11832:       ncova++;
                   11833:       TvarA[ncova]=Tvar[k];
                   11834:       TvarAind[ncova]=k;
1.349     brouard  11835:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11836:       /** 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  11837:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11838:        Fixed[k]= 2;
                   11839:        Dummy[k]= 2;
                   11840:        modell[k].maintype= ATYPE;
                   11841:        modell[k].subtype= APFD;
1.349     brouard  11842:        ncovta++;
                   11843:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   11844:        TvarAVVAind[ncovta]=k;
1.240     brouard  11845:        /* ncoveff++; */
1.227     brouard  11846:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11847:        Fixed[k]= 2;
                   11848:        Dummy[k]= 3;
                   11849:        modell[k].maintype= ATYPE;
                   11850:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  11851:        ncovta++;
                   11852:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11853:        TvarAVVAind[ncovta]=k;
1.240     brouard  11854:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11855:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11856:        Fixed[k]= 3;
                   11857:        Dummy[k]= 2;
                   11858:        modell[k].maintype= ATYPE;
                   11859:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  11860:        ncovva++;
                   11861:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11862:        TvarVVAind[ncovva]=k;
                   11863:        ncovta++;
                   11864:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   11865:        TvarAVVAind[ncovta]=k;
1.240     brouard  11866:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11867:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11868:        Fixed[k]= 3;
                   11869:        Dummy[k]= 3;
                   11870:        modell[k].maintype= ATYPE;
                   11871:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  11872:        ncovva++;
                   11873:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   11874:        TvarVVAind[ncovva]=k;
                   11875:        ncovta++;
                   11876:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   11877:        TvarAVVAind[ncovta]=k;
1.240     brouard  11878:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11879:       }
1.349     brouard  11880:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   11881:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   11882:       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 */
                   11883:       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]]);
                   11884:        Fixed[k]= 0;
                   11885:        Dummy[k]= 0;
                   11886:        ncoveff++;
                   11887:        ncovf++;
                   11888:        /* ncovv++; */
                   11889:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   11890:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11891:        /* ncovv++; */
                   11892:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   11893:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11894:        modell[k].maintype= FTYPE;
                   11895:        TvarF[ncovf]=Tvar[k];
                   11896:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   11897:        TvarFind[ncovf]=k;
                   11898:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11899:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11900:       }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  */
                   11901:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11902:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   11903:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11904:        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 */
                   11905:        ncovvt++;
                   11906:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11907:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11908:        ncovvt++;
                   11909:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11910:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11911:        
                   11912:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   11913:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   11914:        
                   11915:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11916:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   11917:            Fixed[k]= 1;
                   11918:            Dummy[k]= 0;
                   11919:            modell[k].maintype= FTYPE;
                   11920:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   11921:            ncovf++; /* Fixed variables without age */
                   11922:            TvarF[ncovf]=Tvar[k];
                   11923:            TvarFind[ncovf]=k;
                   11924:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11925:            Fixed[k]= 0;  /* Fixed product */
                   11926:            Dummy[k]= 1;
                   11927:            modell[k].maintype= FTYPE;
                   11928:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   11929:            ncovf++; /* Varying variables without age */
                   11930:            TvarF[ncovf]=Tvar[k];
                   11931:            TvarFind[ncovf]=k;
                   11932:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   11933:            Fixed[k]= 1;
                   11934:            Dummy[k]= 0;
                   11935:            modell[k].maintype= VTYPE;
                   11936:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   11937:            ncovv++; /* Varying variables without age */
                   11938:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11939:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11940:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   11941:            Fixed[k]= 1;
                   11942:            Dummy[k]= 1;
                   11943:            modell[k].maintype= VTYPE;
                   11944:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   11945:            ncovv++; /* Varying variables without age */
                   11946:            TvarV[ncovv]=Tvar[k];
                   11947:            TvarVind[ncovv]=k;
                   11948:          }
                   11949:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11950:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11951:            Fixed[k]= 0;  /*  Fixed product */
                   11952:            Dummy[k]= 1;
                   11953:            modell[k].maintype= FTYPE;
                   11954:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   11955:            ncovf++; /* Fixed variables without age */
                   11956:            TvarF[ncovf]=Tvar[k];
                   11957:            TvarFind[ncovf]=k;
                   11958:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   11959:            Fixed[k]= 1;
                   11960:            Dummy[k]= 1;
                   11961:            modell[k].maintype= VTYPE;
                   11962:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   11963:            ncovv++; /* Varying variables without age */
                   11964:            TvarV[ncovv]=Tvar[k];
                   11965:            TvarVind[ncovv]=k;
                   11966:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   11967:            Fixed[k]= 1;
                   11968:            Dummy[k]= 1;
                   11969:            modell[k].maintype= VTYPE;
                   11970:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   11971:            ncovv++; /* Varying variables without age */
                   11972:            TvarV[ncovv]=Tvar[k];
                   11973:            TvarVind[ncovv]=k;
                   11974:            ncovv++; /* Varying variables without age */
                   11975:            TvarV[ncovv]=Tvar[k];
                   11976:            TvarVind[ncovv]=k;
                   11977:          }
                   11978:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   11979:          if(Tvard[k1][2] <=ncovcol){
                   11980:            Fixed[k]= 1;
                   11981:            Dummy[k]= 1;
                   11982:            modell[k].maintype= VTYPE;
                   11983:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   11984:            ncovv++; /* Varying variables without age */
                   11985:            TvarV[ncovv]=Tvar[k];
                   11986:            TvarVind[ncovv]=k;
                   11987:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11988:            Fixed[k]= 1;
                   11989:            Dummy[k]= 1;
                   11990:            modell[k].maintype= VTYPE;
                   11991:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   11992:            ncovv++; /* Varying variables without age */
                   11993:            TvarV[ncovv]=Tvar[k];
                   11994:            TvarVind[ncovv]=k;
                   11995:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11996:            Fixed[k]= 1;
                   11997:            Dummy[k]= 0;
                   11998:            modell[k].maintype= VTYPE;
                   11999:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12000:            ncovv++; /* Varying variables without age */
                   12001:            TvarV[ncovv]=Tvar[k];
                   12002:            TvarVind[ncovv]=k;
                   12003:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12004:            Fixed[k]= 1;
                   12005:            Dummy[k]= 1;
                   12006:            modell[k].maintype= VTYPE;
                   12007:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12008:            ncovv++; /* Varying variables without age */
                   12009:            TvarV[ncovv]=Tvar[k];
                   12010:            TvarVind[ncovv]=k;
                   12011:          }
                   12012:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12013:          if(Tvard[k1][2] <=ncovcol){
                   12014:            Fixed[k]= 1;
                   12015:            Dummy[k]= 1;
                   12016:            modell[k].maintype= VTYPE;
                   12017:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12018:            ncovv++; /* Varying variables without age */
                   12019:            TvarV[ncovv]=Tvar[k];
                   12020:            TvarVind[ncovv]=k;
                   12021:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12022:            Fixed[k]= 1;
                   12023:            Dummy[k]= 1;
                   12024:            modell[k].maintype= VTYPE;
                   12025:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12026:            ncovv++; /* Varying variables without age */
                   12027:            TvarV[ncovv]=Tvar[k];
                   12028:            TvarVind[ncovv]=k;
                   12029:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12030:            Fixed[k]= 1;
                   12031:            Dummy[k]= 1;
                   12032:            modell[k].maintype= VTYPE;
                   12033:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12034:            ncovv++; /* Varying variables without age */
                   12035:            TvarV[ncovv]=Tvar[k];
                   12036:            TvarVind[ncovv]=k;
                   12037:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12038:            Fixed[k]= 1;
                   12039:            Dummy[k]= 1;
                   12040:            modell[k].maintype= VTYPE;
                   12041:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12042:            ncovv++; /* Varying variables without age */
                   12043:            TvarV[ncovv]=Tvar[k];
                   12044:            TvarVind[ncovv]=k;
                   12045:          }
                   12046:        }else{
                   12047:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12048:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12049:        } /*end k1*/
                   12050:       }
                   12051:     }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  12052:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  12053:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12054:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12055:       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 */
                   12056:       ncova++;
                   12057:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12058:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12059:       ncova++;
                   12060:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12061:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  12062: 
1.349     brouard  12063:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12064:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12065:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12066:        ncovta++;
                   12067:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12068:        TvarAVVAind[ncovta]=k;
                   12069:        ncovta++;
                   12070:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12071:        TvarAVVAind[ncovta]=k;
                   12072:       }else{
                   12073:        ncovva++;  /* HERY  reached */
                   12074:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12075:        TvarVVAind[ncovva]=k;
                   12076:        ncovva++;
                   12077:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12078:        TvarVVAind[ncovva]=k;
                   12079:        ncovta++;
                   12080:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12081:        TvarAVVAind[ncovta]=k;
                   12082:        ncovta++;
                   12083:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12084:        TvarAVVAind[ncovta]=k;
                   12085:       }
1.339     brouard  12086:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12087:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  12088:          Fixed[k]= 2;
                   12089:          Dummy[k]= 2;
1.240     brouard  12090:          modell[k].maintype= FTYPE;
                   12091:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  12092:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12093:          /* TvarFind[ncova]=k; */
1.339     brouard  12094:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  12095:          Fixed[k]= 2;  /* Fixed product */
                   12096:          Dummy[k]= 3;
1.240     brouard  12097:          modell[k].maintype= FTYPE;
                   12098:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  12099:          /* TvarF[ncova]=Tvar[k]; */
                   12100:          /* TvarFind[ncova]=k; */
1.339     brouard  12101:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  12102:          Fixed[k]= 3;
                   12103:          Dummy[k]= 2;
1.240     brouard  12104:          modell[k].maintype= VTYPE;
                   12105:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  12106:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12107:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  12108:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  12109:          Fixed[k]= 3;
                   12110:          Dummy[k]= 3;
1.240     brouard  12111:          modell[k].maintype= VTYPE;
                   12112:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  12113:          /* ncovv++; /\* Varying variables without age *\/ */
                   12114:          /* TvarV[ncovv]=Tvar[k]; */
                   12115:          /* TvarVind[ncovv]=k; */
1.240     brouard  12116:        }
1.339     brouard  12117:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12118:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  12119:          Fixed[k]= 2;  /*  Fixed product */
                   12120:          Dummy[k]= 2;
1.240     brouard  12121:          modell[k].maintype= FTYPE;
                   12122:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  12123:          /* ncova++; /\* Fixed variables with age *\/ */
                   12124:          /* TvarF[ncovf]=Tvar[k]; */
                   12125:          /* TvarFind[ncovf]=k; */
1.339     brouard  12126:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  12127:          Fixed[k]= 2;
                   12128:          Dummy[k]= 3;
1.240     brouard  12129:          modell[k].maintype= VTYPE;
                   12130:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  12131:          /* ncova++; /\* Varying variables with age *\/ */
                   12132:          /* TvarV[ncova]=Tvar[k]; */
                   12133:          /* TvarVind[ncova]=k; */
1.339     brouard  12134:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  12135:          Fixed[k]= 3;
                   12136:          Dummy[k]= 2;
1.240     brouard  12137:          modell[k].maintype= VTYPE;
                   12138:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  12139:          ncova++; /* Varying variables without age */
                   12140:          TvarV[ncova]=Tvar[k];
                   12141:          TvarVind[ncova]=k;
                   12142:          /* ncova++; /\* Varying variables without age *\/ */
                   12143:          /* TvarV[ncova]=Tvar[k]; */
                   12144:          /* TvarVind[ncova]=k; */
1.240     brouard  12145:        }
1.339     brouard  12146:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  12147:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12148:          Fixed[k]= 2;
                   12149:          Dummy[k]= 2;
1.240     brouard  12150:          modell[k].maintype= VTYPE;
                   12151:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  12152:          /* ncova++; /\* Varying variables with age *\/ */
                   12153:          /* TvarV[ncova]=Tvar[k]; */
                   12154:          /* TvarVind[ncova]=k; */
1.240     brouard  12155:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12156:          Fixed[k]= 2;
                   12157:          Dummy[k]= 3;
1.240     brouard  12158:          modell[k].maintype= VTYPE;
                   12159:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  12160:          /* ncova++; /\* Varying variables with age *\/ */
                   12161:          /* TvarV[ncova]=Tvar[k]; */
                   12162:          /* TvarVind[ncova]=k; */
1.240     brouard  12163:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12164:          Fixed[k]= 3;
                   12165:          Dummy[k]= 2;
1.240     brouard  12166:          modell[k].maintype= VTYPE;
                   12167:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  12168:          /* ncova++; /\* Varying variables with age *\/ */
                   12169:          /* TvarV[ncova]=Tvar[k]; */
                   12170:          /* TvarVind[ncova]=k; */
1.240     brouard  12171:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12172:          Fixed[k]= 3;
                   12173:          Dummy[k]= 3;
1.240     brouard  12174:          modell[k].maintype= VTYPE;
                   12175:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  12176:          /* ncova++; /\* Varying variables with age *\/ */
                   12177:          /* TvarV[ncova]=Tvar[k]; */
                   12178:          /* TvarVind[ncova]=k; */
1.240     brouard  12179:        }
1.339     brouard  12180:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  12181:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  12182:          Fixed[k]= 2;
                   12183:          Dummy[k]= 2;
1.240     brouard  12184:          modell[k].maintype= VTYPE;
                   12185:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  12186:          /* ncova++; /\* Varying variables with age *\/ */
                   12187:          /* TvarV[ncova]=Tvar[k]; */
                   12188:          /* TvarVind[ncova]=k; */
1.240     brouard  12189:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  12190:          Fixed[k]= 2;
                   12191:          Dummy[k]= 3;
1.240     brouard  12192:          modell[k].maintype= VTYPE;
                   12193:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  12194:          /* ncova++; /\* Varying variables with age *\/ */
                   12195:          /* TvarV[ncova]=Tvar[k]; */
                   12196:          /* TvarVind[ncova]=k; */
1.240     brouard  12197:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  12198:          Fixed[k]= 3;
                   12199:          Dummy[k]= 2;
1.240     brouard  12200:          modell[k].maintype= VTYPE;
                   12201:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  12202:          /* ncova++; /\* Varying variables with age *\/ */
                   12203:          /* TvarV[ncova]=Tvar[k]; */
                   12204:          /* TvarVind[ncova]=k; */
1.240     brouard  12205:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  12206:          Fixed[k]= 3;
                   12207:          Dummy[k]= 3;
1.240     brouard  12208:          modell[k].maintype= VTYPE;
                   12209:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  12210:          /* ncova++; /\* Varying variables with age *\/ */
                   12211:          /* TvarV[ncova]=Tvar[k]; */
                   12212:          /* TvarVind[ncova]=k; */
1.240     brouard  12213:        }
1.227     brouard  12214:       }else{
1.240     brouard  12215:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12216:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12217:       } /*end k1*/
1.349     brouard  12218:     } else{
1.226     brouard  12219:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12220:       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  12221:     }
1.342     brouard  12222:     /* 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]); */
                   12223:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  12224:     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]);
                   12225:   }
1.349     brouard  12226:   ncovvta=ncovva;
1.227     brouard  12227:   /* Searching for doublons in the model */
                   12228:   for(k1=1; k1<= cptcovt;k1++){
                   12229:     for(k2=1; k2 <k1;k2++){
1.285     brouard  12230:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12231:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  12232:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12233:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  12234:            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]);
                   12235:            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  12236:            return(1);
                   12237:          }
                   12238:        }else if (Typevar[k1] ==2){
                   12239:          k3=Tposprod[k1];
                   12240:          k4=Tposprod[k2];
                   12241:          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  12242:            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]]);
                   12243:            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  12244:            return(1);
                   12245:          }
                   12246:        }
1.227     brouard  12247:       }
                   12248:     }
1.225     brouard  12249:   }
                   12250:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12251:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  12252:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12253:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  12254: 
                   12255:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  12256:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  12257:   /*endread:*/
1.225     brouard  12258:   printf("Exiting decodemodel: ");
                   12259:   return (1);
1.136     brouard  12260: }
                   12261: 
1.169     brouard  12262: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  12263: {/* Check ages at death */
1.136     brouard  12264:   int i, m;
1.218     brouard  12265:   int firstone=0;
                   12266:   
1.136     brouard  12267:   for (i=1; i<=imx; i++) {
                   12268:     for(m=2; (m<= maxwav); m++) {
                   12269:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12270:        anint[m][i]=9999;
1.216     brouard  12271:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12272:          s[m][i]=-1;
1.136     brouard  12273:       }
                   12274:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  12275:        *nberr = *nberr + 1;
1.218     brouard  12276:        if(firstone == 0){
                   12277:          firstone=1;
1.260     brouard  12278:        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  12279:        }
1.262     brouard  12280:        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  12281:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  12282:       }
                   12283:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  12284:        (*nberr)++;
1.259     brouard  12285:        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  12286:        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  12287:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  12288:       }
                   12289:     }
                   12290:   }
                   12291: 
                   12292:   for (i=1; i<=imx; i++)  {
                   12293:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12294:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  12295:       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  12296:        if (s[m][i] >= nlstate+1) {
1.169     brouard  12297:          if(agedc[i]>0){
                   12298:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  12299:              agev[m][i]=agedc[i];
1.214     brouard  12300:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  12301:            }else {
1.136     brouard  12302:              if ((int)andc[i]!=9999){
                   12303:                nbwarn++;
                   12304:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12305:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12306:                agev[m][i]=-1;
                   12307:              }
                   12308:            }
1.169     brouard  12309:          } /* agedc > 0 */
1.214     brouard  12310:        } /* end if */
1.136     brouard  12311:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12312:                                 years but with the precision of a month */
                   12313:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12314:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12315:            agev[m][i]=1;
                   12316:          else if(agev[m][i] < *agemin){ 
                   12317:            *agemin=agev[m][i];
                   12318:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12319:          }
                   12320:          else if(agev[m][i] >*agemax){
                   12321:            *agemax=agev[m][i];
1.156     brouard  12322:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  12323:          }
                   12324:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12325:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  12326:        } /* en if 9*/
1.136     brouard  12327:        else { /* =9 */
1.214     brouard  12328:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  12329:          agev[m][i]=1;
                   12330:          s[m][i]=-1;
                   12331:        }
                   12332:       }
1.214     brouard  12333:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  12334:        agev[m][i]=1;
1.214     brouard  12335:       else{
                   12336:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12337:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12338:        agev[m][i]=0;
                   12339:       }
                   12340:     } /* End for lastpass */
                   12341:   }
1.136     brouard  12342:     
                   12343:   for (i=1; i<=imx; i++)  {
                   12344:     for(m=firstpass; (m<=lastpass); m++){
                   12345:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  12346:        (*nberr)++;
1.136     brouard  12347:        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);     
                   12348:        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);     
                   12349:        return 1;
                   12350:       }
                   12351:     }
                   12352:   }
                   12353: 
                   12354:   /*for (i=1; i<=imx; i++){
                   12355:   for (m=firstpass; (m<lastpass); m++){
                   12356:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12357: }
                   12358: 
                   12359: }*/
                   12360: 
                   12361: 
1.139     brouard  12362:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12363:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  12364: 
                   12365:   return (0);
1.164     brouard  12366:  /* endread:*/
1.136     brouard  12367:     printf("Exiting calandcheckages: ");
                   12368:     return (1);
                   12369: }
                   12370: 
1.172     brouard  12371: #if defined(_MSC_VER)
                   12372: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12373: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12374: //#include "stdafx.h"
                   12375: //#include <stdio.h>
                   12376: //#include <tchar.h>
                   12377: //#include <windows.h>
                   12378: //#include <iostream>
                   12379: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12380: 
                   12381: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12382: 
                   12383: BOOL IsWow64()
                   12384: {
                   12385:        BOOL bIsWow64 = FALSE;
                   12386: 
                   12387:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12388:        //  (HANDLE, PBOOL);
                   12389: 
                   12390:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12391: 
                   12392:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12393:        const char funcName[] = "IsWow64Process";
                   12394:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12395:                GetProcAddress(module, funcName);
                   12396: 
                   12397:        if (NULL != fnIsWow64Process)
                   12398:        {
                   12399:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12400:                        &bIsWow64))
                   12401:                        //throw std::exception("Unknown error");
                   12402:                        printf("Unknown error\n");
                   12403:        }
                   12404:        return bIsWow64 != FALSE;
                   12405: }
                   12406: #endif
1.177     brouard  12407: 
1.191     brouard  12408: void syscompilerinfo(int logged)
1.292     brouard  12409: {
                   12410: #include <stdint.h>
                   12411: 
                   12412:   /* #include "syscompilerinfo.h"*/
1.185     brouard  12413:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12414:    /* /GS /W3 /Gy
                   12415:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12416:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12417:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  12418:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12419:    */ 
                   12420:    /* 64 bits */
1.185     brouard  12421:    /*
                   12422:      /GS /W3 /Gy
                   12423:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12424:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12425:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12426:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12427:    /* Optimization are useless and O3 is slower than O2 */
                   12428:    /*
                   12429:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12430:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12431:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12432:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12433:    */
1.186     brouard  12434:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  12435:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12436:       /PDB:"visual studio
                   12437:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12438:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12439:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12440:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12441:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12442:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12443:       uiAccess='false'"
                   12444:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12445:       /NOLOGO /TLBID:1
                   12446:    */
1.292     brouard  12447: 
                   12448: 
1.177     brouard  12449: #if defined __INTEL_COMPILER
1.178     brouard  12450: #if defined(__GNUC__)
                   12451:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12452: #endif
1.177     brouard  12453: #elif defined(__GNUC__) 
1.179     brouard  12454: #ifndef  __APPLE__
1.174     brouard  12455: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  12456: #endif
1.177     brouard  12457:    struct utsname sysInfo;
1.178     brouard  12458:    int cross = CROSS;
                   12459:    if (cross){
                   12460:           printf("Cross-");
1.191     brouard  12461:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  12462:    }
1.174     brouard  12463: #endif
                   12464: 
1.191     brouard  12465:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  12466: #if defined(__clang__)
1.191     brouard  12467:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  12468: #endif
                   12469: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  12470:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  12471: #endif
                   12472: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  12473:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  12474: #endif
                   12475: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  12476:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  12477: #endif
                   12478: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  12479:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  12480: #endif
                   12481: #if defined(_MSC_VER)
1.191     brouard  12482:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  12483: #endif
                   12484: #if defined(__PGI)
1.191     brouard  12485:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  12486: #endif
                   12487: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  12488:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  12489: #endif
1.191     brouard  12490:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  12491:    
1.167     brouard  12492: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12493: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12494:     // Windows (x64 and x86)
1.191     brouard  12495:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  12496: #elif __unix__ // all unices, not all compilers
                   12497:     // Unix
1.191     brouard  12498:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  12499: #elif __linux__
                   12500:     // linux
1.191     brouard  12501:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  12502: #elif __APPLE__
1.174     brouard  12503:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  12504:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  12505: #endif
                   12506: 
                   12507: /*  __MINGW32__          */
                   12508: /*  __CYGWIN__  */
                   12509: /* __MINGW64__  */
                   12510: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12511: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12512: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12513: /* _WIN64  // Defined for applications for Win64. */
                   12514: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12515: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  12516: 
1.167     brouard  12517: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  12518:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  12519: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  12520:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  12521: #else
1.191     brouard  12522:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  12523: #endif
                   12524: 
1.169     brouard  12525: #if defined(__GNUC__)
                   12526: # if defined(__GNUC_PATCHLEVEL__)
                   12527: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12528:                             + __GNUC_MINOR__ * 100 \
                   12529:                             + __GNUC_PATCHLEVEL__)
                   12530: # else
                   12531: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12532:                             + __GNUC_MINOR__ * 100)
                   12533: # endif
1.174     brouard  12534:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  12535:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  12536: 
                   12537:    if (uname(&sysInfo) != -1) {
                   12538:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  12539:         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  12540:    }
                   12541:    else
                   12542:       perror("uname() error");
1.179     brouard  12543:    //#ifndef __INTEL_COMPILER 
                   12544: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  12545:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  12546:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  12547: #endif
1.169     brouard  12548: #endif
1.172     brouard  12549: 
1.286     brouard  12550:    //   void main ()
1.172     brouard  12551:    //   {
1.169     brouard  12552: #if defined(_MSC_VER)
1.174     brouard  12553:    if (IsWow64()){
1.191     brouard  12554:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12555:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  12556:    }
                   12557:    else{
1.191     brouard  12558:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12559:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  12560:    }
1.172     brouard  12561:    //     printf("\nPress Enter to continue...");
                   12562:    //     getchar();
                   12563:    //   }
                   12564: 
1.169     brouard  12565: #endif
                   12566:    
1.167     brouard  12567: 
1.219     brouard  12568: }
1.136     brouard  12569: 
1.219     brouard  12570: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  12571:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  12572:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  12573:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  12574:   /* double ftolpl = 1.e-10; */
1.180     brouard  12575:   double age, agebase, agelim;
1.203     brouard  12576:   double tot;
1.180     brouard  12577: 
1.202     brouard  12578:   strcpy(filerespl,"PL_");
                   12579:   strcat(filerespl,fileresu);
                   12580:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  12581:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12582:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  12583:   }
1.288     brouard  12584:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12585:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  12586:   pstamp(ficrespl);
1.288     brouard  12587:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  12588:   fprintf(ficrespl,"#Age ");
                   12589:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12590:   fprintf(ficrespl,"\n");
1.180     brouard  12591:   
1.219     brouard  12592:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  12593: 
1.219     brouard  12594:   agebase=ageminpar;
                   12595:   agelim=agemaxpar;
1.180     brouard  12596: 
1.227     brouard  12597:   /* i1=pow(2,ncoveff); */
1.234     brouard  12598:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  12599:   if (cptcovn < 1){i1=1;}
1.180     brouard  12600: 
1.337     brouard  12601:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  12602:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12603:       k=TKresult[nres];
1.338     brouard  12604:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12605:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12606:       /*       continue; */
1.235     brouard  12607: 
1.238     brouard  12608:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12609:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12610:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12611:       /* k=k+1; */
                   12612:       /* to clean */
1.332     brouard  12613:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  12614:       fprintf(ficrespl,"#******");
                   12615:       printf("#******");
                   12616:       fprintf(ficlog,"#******");
1.337     brouard  12617:       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  12618:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  12619:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12620:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12621:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12622:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12623:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12624:       }
                   12625:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12626:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12627:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12628:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12629:       /* } */
1.238     brouard  12630:       fprintf(ficrespl,"******\n");
                   12631:       printf("******\n");
                   12632:       fprintf(ficlog,"******\n");
                   12633:       if(invalidvarcomb[k]){
                   12634:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12635:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12636:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12637:        continue;
                   12638:       }
1.219     brouard  12639: 
1.238     brouard  12640:       fprintf(ficrespl,"#Age ");
1.337     brouard  12641:       /* for(j=1;j<=cptcoveff;j++) { */
                   12642:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12643:       /* } */
                   12644:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12645:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12646:       }
                   12647:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12648:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  12649:     
1.238     brouard  12650:       for (age=agebase; age<=agelim; age++){
                   12651:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  12652:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12653:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  12654:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  12655:        /* for(j=1;j<=cptcoveff;j++) */
                   12656:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12657:        for(j=1;j<=cptcovs;j++)
                   12658:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12659:        tot=0.;
                   12660:        for(i=1; i<=nlstate;i++){
                   12661:          tot +=  prlim[i][i];
                   12662:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12663:        }
                   12664:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12665:       } /* Age */
                   12666:       /* was end of cptcod */
1.337     brouard  12667:     } /* nres */
                   12668:   /* } /\* for each combination *\/ */
1.219     brouard  12669:   return 0;
1.180     brouard  12670: }
                   12671: 
1.218     brouard  12672: 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  12673:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  12674:        
                   12675:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12676:    * at any age between ageminpar and agemaxpar
                   12677:         */
1.235     brouard  12678:   int i, j, k, i1, nres=0 ;
1.217     brouard  12679:   /* double ftolpl = 1.e-10; */
                   12680:   double age, agebase, agelim;
                   12681:   double tot;
1.218     brouard  12682:   /* double ***mobaverage; */
                   12683:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12684: 
                   12685:   strcpy(fileresplb,"PLB_");
                   12686:   strcat(fileresplb,fileresu);
                   12687:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12688:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12689:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12690:   }
1.288     brouard  12691:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12692:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12693:   pstamp(ficresplb);
1.288     brouard  12694:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12695:   fprintf(ficresplb,"#Age ");
                   12696:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12697:   fprintf(ficresplb,"\n");
                   12698:   
1.218     brouard  12699:   
                   12700:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12701:   
                   12702:   agebase=ageminpar;
                   12703:   agelim=agemaxpar;
                   12704:   
                   12705:   
1.227     brouard  12706:   i1=pow(2,cptcoveff);
1.218     brouard  12707:   if (cptcovn < 1){i1=1;}
1.227     brouard  12708:   
1.238     brouard  12709:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12710:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12711:       k=TKresult[nres];
                   12712:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12713:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12714:      /*        continue; */
                   12715:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12716:       fprintf(ficresplb,"#******");
                   12717:       printf("#******");
                   12718:       fprintf(ficlog,"#******");
1.338     brouard  12719:       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) */
                   12720:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12721:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12722:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12723:       }
1.338     brouard  12724:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12725:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12726:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12727:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12728:       /* } */
                   12729:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12730:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12731:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12732:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12733:       /* } */
1.238     brouard  12734:       fprintf(ficresplb,"******\n");
                   12735:       printf("******\n");
                   12736:       fprintf(ficlog,"******\n");
                   12737:       if(invalidvarcomb[k]){
                   12738:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12739:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12740:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12741:        continue;
                   12742:       }
1.218     brouard  12743:     
1.238     brouard  12744:       fprintf(ficresplb,"#Age ");
1.338     brouard  12745:       for(j=1;j<=cptcovs;j++) {
                   12746:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12747:       }
                   12748:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12749:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12750:     
                   12751:     
1.238     brouard  12752:       for (age=agebase; age<=agelim; age++){
                   12753:        /* for (age=agebase; age<=agebase; age++){ */
                   12754:        if(mobilavproj > 0){
                   12755:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12756:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12757:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12758:        }else if (mobilavproj == 0){
                   12759:          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);
                   12760:          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);
                   12761:          exit(1);
                   12762:        }else{
                   12763:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12764:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12765:          /* printf("TOTOT\n"); */
                   12766:           /* exit(1); */
1.238     brouard  12767:        }
                   12768:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12769:        for(j=1;j<=cptcovs;j++)
                   12770:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12771:        tot=0.;
                   12772:        for(i=1; i<=nlstate;i++){
                   12773:          tot +=  bprlim[i][i];
                   12774:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12775:        }
                   12776:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12777:       } /* Age */
                   12778:       /* was end of cptcod */
1.255     brouard  12779:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12780:     /* } /\* end of any combination *\/ */
1.238     brouard  12781:   } /* end of nres */  
1.218     brouard  12782:   /* hBijx(p, bage, fage); */
                   12783:   /* fclose(ficrespijb); */
                   12784:   
                   12785:   return 0;
1.217     brouard  12786: }
1.218     brouard  12787:  
1.180     brouard  12788: int hPijx(double *p, int bage, int fage){
                   12789:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12790:   /* to be optimized with precov */
1.180     brouard  12791:   int stepsize;
                   12792:   int agelim;
                   12793:   int hstepm;
                   12794:   int nhstepm;
1.235     brouard  12795:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12796: 
                   12797:   double agedeb;
                   12798:   double ***p3mat;
                   12799: 
1.337     brouard  12800:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12801:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12802:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12803:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12804:   }
                   12805:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12806:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12807:   
                   12808:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12809:   /*if (stepm<=24) stepsize=2;*/
                   12810:   
                   12811:   agelim=AGESUP;
                   12812:   hstepm=stepsize*YEARM; /* Every year of age */
                   12813:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12814:   
                   12815:   /* hstepm=1;   aff par mois*/
                   12816:   pstamp(ficrespij);
                   12817:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12818:   i1= pow(2,cptcoveff);
                   12819:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12820:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12821:   /*   k=k+1;  */
                   12822:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12823:     k=TKresult[nres];
1.338     brouard  12824:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12825:     /* for(k=1; k<=i1;k++){ */
                   12826:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12827:     /*         continue; */
                   12828:     fprintf(ficrespij,"\n#****** ");
                   12829:     for(j=1;j<=cptcovs;j++){
                   12830:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12831:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12832:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12833:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12834:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12835:     }
                   12836:     fprintf(ficrespij,"******\n");
                   12837:     
                   12838:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12839:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12840:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12841:       
                   12842:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12843:       
                   12844:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12845:       oldm=oldms;savm=savms;
                   12846:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12847:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12848:       for(i=1; i<=nlstate;i++)
                   12849:        for(j=1; j<=nlstate+ndeath;j++)
                   12850:          fprintf(ficrespij," %1d-%1d",i,j);
                   12851:       fprintf(ficrespij,"\n");
                   12852:       for (h=0; h<=nhstepm; h++){
                   12853:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12854:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12855:        for(i=1; i<=nlstate;i++)
                   12856:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12857:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12858:        fprintf(ficrespij,"\n");
                   12859:       }
1.337     brouard  12860:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12861:       fprintf(ficrespij,"\n");
1.180     brouard  12862:     }
1.337     brouard  12863:   }
                   12864:   /*}*/
                   12865:   return 0;
1.180     brouard  12866: }
1.218     brouard  12867:  
                   12868:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12869:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12870:     /* To be optimized with precov */
1.217     brouard  12871:   int stepsize;
1.218     brouard  12872:   /* int agelim; */
                   12873:        int ageminl;
1.217     brouard  12874:   int hstepm;
                   12875:   int nhstepm;
1.238     brouard  12876:   int h, i, i1, j, k, nres;
1.218     brouard  12877:        
1.217     brouard  12878:   double agedeb;
                   12879:   double ***p3mat;
1.218     brouard  12880:        
                   12881:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12882:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12883:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12884:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12885:   }
                   12886:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12887:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12888:   
                   12889:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12890:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12891:   
1.218     brouard  12892:   /* agelim=AGESUP; */
1.289     brouard  12893:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12894:   hstepm=stepsize*YEARM; /* Every year of age */
                   12895:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12896:   
                   12897:   /* hstepm=1;   aff par mois*/
                   12898:   pstamp(ficrespijb);
1.255     brouard  12899:   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  12900:   i1= pow(2,cptcoveff);
1.218     brouard  12901:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12902:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12903:   /*   k=k+1;  */
1.238     brouard  12904:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12905:     k=TKresult[nres];
1.338     brouard  12906:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12907:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12908:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12909:     /*         continue; */
                   12910:     fprintf(ficrespijb,"\n#****** ");
                   12911:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12912:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12913:       /* for(j=1;j<=cptcoveff;j++) */
                   12914:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12915:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12916:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12917:     }
                   12918:     fprintf(ficrespijb,"******\n");
                   12919:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12920:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12921:       continue;
                   12922:     }
                   12923:     
                   12924:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12925:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12926:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12927:       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 */
                   12928:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12929:       
                   12930:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12931:       
                   12932:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12933:       /* and memory limitations if stepm is small */
                   12934:       
                   12935:       /* oldm=oldms;savm=savms; */
                   12936:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12937:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12938:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12939:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12940:       for(i=1; i<=nlstate;i++)
                   12941:        for(j=1; j<=nlstate+ndeath;j++)
                   12942:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12943:       fprintf(ficrespijb,"\n");
                   12944:       for (h=0; h<=nhstepm; h++){
                   12945:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12946:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12947:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12948:        for(i=1; i<=nlstate;i++)
                   12949:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12950:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12951:        fprintf(ficrespijb,"\n");
1.337     brouard  12952:       }
                   12953:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12954:       fprintf(ficrespijb,"\n");
                   12955:     } /* end age deb */
                   12956:     /* } /\* end combination *\/ */
1.238     brouard  12957:   } /* end nres */
1.218     brouard  12958:   return 0;
                   12959:  } /*  hBijx */
1.217     brouard  12960: 
1.180     brouard  12961: 
1.136     brouard  12962: /***********************************************/
                   12963: /**************** Main Program *****************/
                   12964: /***********************************************/
                   12965: 
                   12966: int main(int argc, char *argv[])
                   12967: {
                   12968: #ifdef GSL
                   12969:   const gsl_multimin_fminimizer_type *T;
                   12970:   size_t iteri = 0, it;
                   12971:   int rval = GSL_CONTINUE;
                   12972:   int status = GSL_SUCCESS;
                   12973:   double ssval;
                   12974: #endif
                   12975:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12976:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12977:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12978:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12979:   int jj, ll, li, lj, lk;
1.136     brouard  12980:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12981:   int num_filled;
1.136     brouard  12982:   int itimes;
                   12983:   int NDIM=2;
                   12984:   int vpopbased=0;
1.235     brouard  12985:   int nres=0;
1.258     brouard  12986:   int endishere=0;
1.277     brouard  12987:   int noffset=0;
1.274     brouard  12988:   int ncurrv=0; /* Temporary variable */
                   12989:   
1.164     brouard  12990:   char ca[32], cb[32];
1.136     brouard  12991:   /*  FILE *fichtm; *//* Html File */
                   12992:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12993:   struct stat info;
1.191     brouard  12994:   double agedeb=0.;
1.194     brouard  12995: 
                   12996:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12997:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12998: 
1.165     brouard  12999:   double fret;
1.191     brouard  13000:   double dum=0.; /* Dummy variable */
1.136     brouard  13001:   double ***p3mat;
1.218     brouard  13002:   /* double ***mobaverage; */
1.319     brouard  13003:   double wald;
1.164     brouard  13004: 
1.351     brouard  13005:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  13006:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13007: 
1.234     brouard  13008:   char  modeltemp[MAXLINE];
1.332     brouard  13009:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  13010:   
1.136     brouard  13011:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  13012:   char *tok, *val; /* pathtot */
1.334     brouard  13013:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  13014:   int c,  h , cpt, c2;
1.191     brouard  13015:   int jl=0;
                   13016:   int i1, j1, jk, stepsize=0;
1.194     brouard  13017:   int count=0;
                   13018: 
1.164     brouard  13019:   int *tab; 
1.136     brouard  13020:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  13021:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13022:   /* double anprojf, mprojf, jprojf; */
                   13023:   /* double jintmean,mintmean,aintmean;   */
                   13024:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13025:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13026:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13027:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13028:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  13029:   int mobilav=0,popforecast=0;
1.191     brouard  13030:   int hstepm=0, nhstepm=0;
1.136     brouard  13031:   int agemortsup;
                   13032:   float  sumlpop=0.;
                   13033:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13034:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13035: 
1.191     brouard  13036:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  13037:   double ftolpl=FTOL;
                   13038:   double **prlim;
1.217     brouard  13039:   double **bprlim;
1.317     brouard  13040:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13041:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  13042:   double ***paramstart; /* Matrix of starting parameter values */
                   13043:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  13044:   double **matcov; /* Matrix of covariance */
1.203     brouard  13045:   double **hess; /* Hessian matrix */
1.136     brouard  13046:   double ***delti3; /* Scale */
                   13047:   double *delti; /* Scale */
                   13048:   double ***eij, ***vareij;
                   13049:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  13050: 
1.136     brouard  13051:   double *epj, vepp;
1.164     brouard  13052: 
1.273     brouard  13053:   double dateprev1, dateprev2;
1.296     brouard  13054:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13055:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13056: 
1.217     brouard  13057: 
1.136     brouard  13058:   double **ximort;
1.145     brouard  13059:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  13060:   int *dcwave;
                   13061: 
1.164     brouard  13062:   char z[1]="c";
1.136     brouard  13063: 
                   13064:   /*char  *strt;*/
                   13065:   char strtend[80];
1.126     brouard  13066: 
1.164     brouard  13067: 
1.126     brouard  13068: /*   setlocale (LC_ALL, ""); */
                   13069: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13070: /*   textdomain (PACKAGE); */
                   13071: /*   setlocale (LC_CTYPE, ""); */
                   13072: /*   setlocale (LC_MESSAGES, ""); */
                   13073: 
                   13074:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  13075:   rstart_time = time(NULL);  
                   13076:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13077:   start_time = *localtime(&rstart_time);
1.126     brouard  13078:   curr_time=start_time;
1.157     brouard  13079:   /*tml = *localtime(&start_time.tm_sec);*/
                   13080:   /* strcpy(strstart,asctime(&tml)); */
                   13081:   strcpy(strstart,asctime(&start_time));
1.126     brouard  13082: 
                   13083: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  13084: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13085: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  13086: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13087: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13088: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  13089: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  13090: /*   strt=asctime(&tmg); */
                   13091: /*   printf("Time(after) =%s",strstart);  */
                   13092: /*  (void) time (&time_value);
                   13093: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13094: *  tm = *localtime(&time_value);
                   13095: *  strstart=asctime(&tm);
                   13096: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13097: */
                   13098: 
                   13099:   nberr=0; /* Number of errors and warnings */
                   13100:   nbwarn=0;
1.184     brouard  13101: #ifdef WIN32
                   13102:   _getcwd(pathcd, size);
                   13103: #else
1.126     brouard  13104:   getcwd(pathcd, size);
1.184     brouard  13105: #endif
1.191     brouard  13106:   syscompilerinfo(0);
1.196     brouard  13107:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  13108:   if(argc <=1){
                   13109:     printf("\nEnter the parameter file name: ");
1.205     brouard  13110:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13111:       printf("ERROR Empty parameter file name\n");
                   13112:       goto end;
                   13113:     }
1.126     brouard  13114:     i=strlen(pathr);
                   13115:     if(pathr[i-1]=='\n')
                   13116:       pathr[i-1]='\0';
1.156     brouard  13117:     i=strlen(pathr);
1.205     brouard  13118:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  13119:       pathr[i-1]='\0';
1.205     brouard  13120:     }
                   13121:     i=strlen(pathr);
                   13122:     if( i==0 ){
                   13123:       printf("ERROR Empty parameter file name\n");
                   13124:       goto end;
                   13125:     }
                   13126:     for (tok = pathr; tok != NULL; ){
1.126     brouard  13127:       printf("Pathr |%s|\n",pathr);
                   13128:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13129:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13130:       strcpy (pathtot, val);
                   13131:       if(pathr[0] == '\0') break; /* Dirty */
                   13132:     }
                   13133:   }
1.281     brouard  13134:   else if (argc<=2){
                   13135:     strcpy(pathtot,argv[1]);
                   13136:   }
1.126     brouard  13137:   else{
                   13138:     strcpy(pathtot,argv[1]);
1.281     brouard  13139:     strcpy(z,argv[2]);
                   13140:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  13141:   }
                   13142:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13143:   /*cygwin_split_path(pathtot,path,optionfile);
                   13144:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13145:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13146: 
                   13147:   /* Split argv[0], imach program to get pathimach */
                   13148:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13149:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13150:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13151:  /*   strcpy(pathimach,argv[0]); */
                   13152:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13153:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13154:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  13155: #ifdef WIN32
                   13156:   _chdir(path); /* Can be a relative path */
                   13157:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13158: #else
1.126     brouard  13159:   chdir(path); /* Can be a relative path */
1.184     brouard  13160:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13161: #endif
                   13162:   printf("Current directory %s!\n",pathcd);
1.126     brouard  13163:   strcpy(command,"mkdir ");
                   13164:   strcat(command,optionfilefiname);
                   13165:   if((outcmd=system(command)) != 0){
1.169     brouard  13166:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  13167:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13168:     /* fclose(ficlog); */
                   13169: /*     exit(1); */
                   13170:   }
                   13171: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13172: /*     perror("mkdir"); */
                   13173: /*   } */
                   13174: 
                   13175:   /*-------- arguments in the command line --------*/
                   13176: 
1.186     brouard  13177:   /* Main Log file */
1.126     brouard  13178:   strcat(filelog, optionfilefiname);
                   13179:   strcat(filelog,".log");    /* */
                   13180:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13181:     printf("Problem with logfile %s\n",filelog);
                   13182:     goto end;
                   13183:   }
                   13184:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  13185:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  13186:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13187:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13188:  path=%s \n\
                   13189:  optionfile=%s\n\
                   13190:  optionfilext=%s\n\
1.156     brouard  13191:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  13192: 
1.197     brouard  13193:   syscompilerinfo(1);
1.167     brouard  13194: 
1.126     brouard  13195:   printf("Local time (at start):%s",strstart);
                   13196:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13197:   fflush(ficlog);
                   13198: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  13199: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  13200: 
                   13201:   /* */
                   13202:   strcpy(fileres,"r");
                   13203:   strcat(fileres, optionfilefiname);
1.201     brouard  13204:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  13205:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  13206:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  13207: 
1.186     brouard  13208:   /* Main ---------arguments file --------*/
1.126     brouard  13209: 
                   13210:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  13211:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13212:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  13213:     fflush(ficlog);
1.149     brouard  13214:     /* goto end; */
                   13215:     exit(70); 
1.126     brouard  13216:   }
                   13217: 
                   13218:   strcpy(filereso,"o");
1.201     brouard  13219:   strcat(filereso,fileresu);
1.126     brouard  13220:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13221:     printf("Problem with Output resultfile: %s\n", filereso);
                   13222:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13223:     fflush(ficlog);
                   13224:     goto end;
                   13225:   }
1.278     brouard  13226:       /*-------- Rewriting parameter file ----------*/
                   13227:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13228:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13229:   strcat(rfileres,".");    /* */
                   13230:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13231:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13232:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13233:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13234:     fflush(ficlog);
                   13235:     goto end;
                   13236:   }
                   13237:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  13238: 
1.278     brouard  13239:                                      
1.126     brouard  13240:   /* Reads comments: lines beginning with '#' */
                   13241:   numlinepar=0;
1.277     brouard  13242:   /* Is it a BOM UTF-8 Windows file? */
                   13243:   /* First parameter line */
1.197     brouard  13244:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  13245:     noffset=0;
                   13246:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13247:     {
                   13248:       noffset=noffset+3;
                   13249:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13250:     }
1.302     brouard  13251: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13252:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  13253:     {
                   13254:       noffset=noffset+2;
                   13255:       printf("# File is an UTF16BE BOM file\n");
                   13256:     }
                   13257:     else if( line[0] == 0 && line[1] == 0)
                   13258:     {
                   13259:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13260:        noffset=noffset+4;
                   13261:        printf("# File is an UTF16BE BOM file\n");
                   13262:       }
                   13263:     } else{
                   13264:       ;/*printf(" Not a BOM file\n");*/
                   13265:     }
                   13266:   
1.197     brouard  13267:     /* If line starts with a # it is a comment */
1.277     brouard  13268:     if (line[noffset] == '#') {
1.197     brouard  13269:       numlinepar++;
                   13270:       fputs(line,stdout);
                   13271:       fputs(line,ficparo);
1.278     brouard  13272:       fputs(line,ficres);
1.197     brouard  13273:       fputs(line,ficlog);
                   13274:       continue;
                   13275:     }else
                   13276:       break;
                   13277:   }
                   13278:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13279:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13280:     if (num_filled != 5) {
                   13281:       printf("Should be 5 parameters\n");
1.283     brouard  13282:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  13283:     }
1.126     brouard  13284:     numlinepar++;
1.197     brouard  13285:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  13286:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13287:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13288:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  13289:   }
                   13290:   /* Second parameter line */
                   13291:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  13292:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13293:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  13294:     if (line[0] == '#') {
                   13295:       numlinepar++;
1.283     brouard  13296:       printf("%s",line);
                   13297:       fprintf(ficres,"%s",line);
                   13298:       fprintf(ficparo,"%s",line);
                   13299:       fprintf(ficlog,"%s",line);
1.197     brouard  13300:       continue;
                   13301:     }else
                   13302:       break;
                   13303:   }
1.223     brouard  13304:   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", \
                   13305:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13306:     if (num_filled != 11) {
                   13307:       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  13308:       printf("but line=%s\n",line);
1.283     brouard  13309:       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");
                   13310:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  13311:     }
1.286     brouard  13312:     if( lastpass > maxwav){
                   13313:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13314:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13315:       fflush(ficlog);
                   13316:       goto end;
                   13317:     }
                   13318:       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  13319:     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  13320:     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  13321:     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  13322:   }
1.203     brouard  13323:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  13324:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  13325:   /* Third parameter line */
                   13326:   while(fgets(line, MAXLINE, ficpar)) {
                   13327:     /* If line starts with a # it is a comment */
                   13328:     if (line[0] == '#') {
                   13329:       numlinepar++;
1.283     brouard  13330:       printf("%s",line);
                   13331:       fprintf(ficres,"%s",line);
                   13332:       fprintf(ficparo,"%s",line);
                   13333:       fprintf(ficlog,"%s",line);
1.197     brouard  13334:       continue;
                   13335:     }else
                   13336:       break;
                   13337:   }
1.351     brouard  13338:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13339:     if (num_filled != 1){
                   13340:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13341:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13342:       model[0]='\0';
                   13343:       goto end;
                   13344:     }else{
                   13345:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13346:       strcpy(line, linetmp);
                   13347:     }
                   13348:   }
                   13349:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  13350:     if (num_filled != 1){
1.302     brouard  13351:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13352:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  13353:       model[0]='\0';
                   13354:       goto end;
                   13355:     }
                   13356:     else{
                   13357:       if (model[0]=='+'){
                   13358:        for(i=1; i<=strlen(model);i++)
                   13359:          modeltemp[i-1]=model[i];
1.201     brouard  13360:        strcpy(model,modeltemp); 
1.197     brouard  13361:       }
                   13362:     }
1.338     brouard  13363:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  13364:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  13365:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13366:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13367:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  13368:   }
                   13369:   /* 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); */
                   13370:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13371:   /* 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  13372:   /* 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); */
                   13373:   /* 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  13374:   fflush(ficlog);
1.190     brouard  13375:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13376:   if(model[0]=='#'){
1.279     brouard  13377:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13378:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13379:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  13380:     if(mle != -1){
1.279     brouard  13381:       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  13382:       exit(1);
                   13383:     }
                   13384:   }
1.126     brouard  13385:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13386:     ungetc(c,ficpar);
                   13387:     fgets(line, MAXLINE, ficpar);
                   13388:     numlinepar++;
1.195     brouard  13389:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13390:       z[0]=line[1];
1.342     brouard  13391:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  13392:       debugILK=1;printf("DebugILK\n");
1.195     brouard  13393:     }
                   13394:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  13395:     fputs(line, stdout);
                   13396:     //puts(line);
1.126     brouard  13397:     fputs(line,ficparo);
                   13398:     fputs(line,ficlog);
                   13399:   }
                   13400:   ungetc(c,ficpar);
                   13401: 
                   13402:    
1.290     brouard  13403:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13404:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13405:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  13406:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13407:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  13408:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13409:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13410:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13411:   */
                   13412:   if (strlen(model)>1) 
1.187     brouard  13413:     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  13414:   else
1.187     brouard  13415:     ncovmodel=2; /* Constant and age */
1.133     brouard  13416:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13417:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  13418:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13419:     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);
                   13420:     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);
                   13421:     fflush(stdout);
                   13422:     fclose (ficlog);
                   13423:     goto end;
                   13424:   }
1.126     brouard  13425:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13426:   delti=delti3[1][1];
                   13427:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13428:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  13429: /* We could also provide initial parameters values giving by simple logistic regression 
                   13430:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13431:       /* for(i=1;i<nlstate;i++){ */
                   13432:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13433:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13434:       /* } */
1.126     brouard  13435:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  13436:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13437:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13438:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13439:     fclose (ficparo);
                   13440:     fclose (ficlog);
                   13441:     goto end;
                   13442:     exit(0);
1.220     brouard  13443:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  13444:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  13445:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13446:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  13447:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13448:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13449:     hess=matrix(1,npar,1,npar);
1.220     brouard  13450:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  13451:     /* Read guessed parameters */
1.126     brouard  13452:     /* Reads comments: lines beginning with '#' */
                   13453:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13454:       ungetc(c,ficpar);
                   13455:       fgets(line, MAXLINE, ficpar);
                   13456:       numlinepar++;
1.141     brouard  13457:       fputs(line,stdout);
1.126     brouard  13458:       fputs(line,ficparo);
                   13459:       fputs(line,ficlog);
                   13460:     }
                   13461:     ungetc(c,ficpar);
                   13462:     
                   13463:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  13464:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  13465:     for(i=1; i <=nlstate; i++){
1.234     brouard  13466:       j=0;
1.126     brouard  13467:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  13468:        if(jj==i) continue;
                   13469:        j++;
1.292     brouard  13470:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13471:          ungetc(c,ficpar);
                   13472:          fgets(line, MAXLINE, ficpar);
                   13473:          numlinepar++;
                   13474:          fputs(line,stdout);
                   13475:          fputs(line,ficparo);
                   13476:          fputs(line,ficlog);
                   13477:        }
                   13478:        ungetc(c,ficpar);
1.234     brouard  13479:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13480:        if ((i1 != i) || (j1 != jj)){
                   13481:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  13482: It might be a problem of design; if ncovcol and the model are correct\n \
                   13483: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  13484:          exit(1);
                   13485:        }
                   13486:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13487:        if(mle==1)
                   13488:          printf("%1d%1d",i,jj);
                   13489:        fprintf(ficlog,"%1d%1d",i,jj);
                   13490:        for(k=1; k<=ncovmodel;k++){
                   13491:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13492:          if(mle==1){
                   13493:            printf(" %lf",param[i][j][k]);
                   13494:            fprintf(ficlog," %lf",param[i][j][k]);
                   13495:          }
                   13496:          else
                   13497:            fprintf(ficlog," %lf",param[i][j][k]);
                   13498:          fprintf(ficparo," %lf",param[i][j][k]);
                   13499:        }
                   13500:        fscanf(ficpar,"\n");
                   13501:        numlinepar++;
                   13502:        if(mle==1)
                   13503:          printf("\n");
                   13504:        fprintf(ficlog,"\n");
                   13505:        fprintf(ficparo,"\n");
1.126     brouard  13506:       }
                   13507:     }  
                   13508:     fflush(ficlog);
1.234     brouard  13509:     
1.251     brouard  13510:     /* Reads parameters values */
1.126     brouard  13511:     p=param[1][1];
1.251     brouard  13512:     pstart=paramstart[1][1];
1.126     brouard  13513:     
                   13514:     /* Reads comments: lines beginning with '#' */
                   13515:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13516:       ungetc(c,ficpar);
                   13517:       fgets(line, MAXLINE, ficpar);
                   13518:       numlinepar++;
1.141     brouard  13519:       fputs(line,stdout);
1.126     brouard  13520:       fputs(line,ficparo);
                   13521:       fputs(line,ficlog);
                   13522:     }
                   13523:     ungetc(c,ficpar);
                   13524: 
                   13525:     for(i=1; i <=nlstate; i++){
                   13526:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  13527:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13528:        if ( (i1-i) * (j1-j) != 0){
                   13529:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13530:          exit(1);
                   13531:        }
                   13532:        printf("%1d%1d",i,j);
                   13533:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13534:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13535:        for(k=1; k<=ncovmodel;k++){
                   13536:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13537:          printf(" %le",delti3[i][j][k]);
                   13538:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13539:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13540:        }
                   13541:        fscanf(ficpar,"\n");
                   13542:        numlinepar++;
                   13543:        printf("\n");
                   13544:        fprintf(ficparo,"\n");
                   13545:        fprintf(ficlog,"\n");
1.126     brouard  13546:       }
                   13547:     }
                   13548:     fflush(ficlog);
1.234     brouard  13549:     
1.145     brouard  13550:     /* Reads covariance matrix */
1.126     brouard  13551:     delti=delti3[1][1];
1.220     brouard  13552:                
                   13553:                
1.126     brouard  13554:     /* 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  13555:                
1.126     brouard  13556:     /* Reads comments: lines beginning with '#' */
                   13557:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13558:       ungetc(c,ficpar);
                   13559:       fgets(line, MAXLINE, ficpar);
                   13560:       numlinepar++;
1.141     brouard  13561:       fputs(line,stdout);
1.126     brouard  13562:       fputs(line,ficparo);
                   13563:       fputs(line,ficlog);
                   13564:     }
                   13565:     ungetc(c,ficpar);
1.220     brouard  13566:                
1.126     brouard  13567:     matcov=matrix(1,npar,1,npar);
1.203     brouard  13568:     hess=matrix(1,npar,1,npar);
1.131     brouard  13569:     for(i=1; i <=npar; i++)
                   13570:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  13571:                
1.194     brouard  13572:     /* Scans npar lines */
1.126     brouard  13573:     for(i=1; i <=npar; i++){
1.226     brouard  13574:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  13575:       if(count != 3){
1.226     brouard  13576:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13577: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13578: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13579:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  13580: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13581: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  13582:        exit(1);
1.220     brouard  13583:       }else{
1.226     brouard  13584:        if(mle==1)
                   13585:          printf("%1d%1d%d",i1,j1,jk);
                   13586:       }
                   13587:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13588:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  13589:       for(j=1; j <=i; j++){
1.226     brouard  13590:        fscanf(ficpar," %le",&matcov[i][j]);
                   13591:        if(mle==1){
                   13592:          printf(" %.5le",matcov[i][j]);
                   13593:        }
                   13594:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13595:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  13596:       }
                   13597:       fscanf(ficpar,"\n");
                   13598:       numlinepar++;
                   13599:       if(mle==1)
1.220     brouard  13600:                                printf("\n");
1.126     brouard  13601:       fprintf(ficlog,"\n");
                   13602:       fprintf(ficparo,"\n");
                   13603:     }
1.194     brouard  13604:     /* End of read covariance matrix npar lines */
1.126     brouard  13605:     for(i=1; i <=npar; i++)
                   13606:       for(j=i+1;j<=npar;j++)
1.226     brouard  13607:        matcov[i][j]=matcov[j][i];
1.126     brouard  13608:     
                   13609:     if(mle==1)
                   13610:       printf("\n");
                   13611:     fprintf(ficlog,"\n");
                   13612:     
                   13613:     fflush(ficlog);
                   13614:     
                   13615:   }    /* End of mle != -3 */
1.218     brouard  13616:   
1.186     brouard  13617:   /*  Main data
                   13618:    */
1.290     brouard  13619:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13620:   /* num=lvector(1,n); */
                   13621:   /* moisnais=vector(1,n); */
                   13622:   /* annais=vector(1,n); */
                   13623:   /* moisdc=vector(1,n); */
                   13624:   /* andc=vector(1,n); */
                   13625:   /* weight=vector(1,n); */
                   13626:   /* agedc=vector(1,n); */
                   13627:   /* cod=ivector(1,n); */
                   13628:   /* for(i=1;i<=n;i++){ */
                   13629:   num=lvector(firstobs,lastobs);
                   13630:   moisnais=vector(firstobs,lastobs);
                   13631:   annais=vector(firstobs,lastobs);
                   13632:   moisdc=vector(firstobs,lastobs);
                   13633:   andc=vector(firstobs,lastobs);
                   13634:   weight=vector(firstobs,lastobs);
                   13635:   agedc=vector(firstobs,lastobs);
                   13636:   cod=ivector(firstobs,lastobs);
                   13637:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  13638:     num[i]=0;
                   13639:     moisnais[i]=0;
                   13640:     annais[i]=0;
                   13641:     moisdc[i]=0;
                   13642:     andc[i]=0;
                   13643:     agedc[i]=0;
                   13644:     cod[i]=0;
                   13645:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13646:   }
1.290     brouard  13647:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13648:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  13649:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  13650:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  13651:   tab=ivector(1,NCOVMAX);
1.144     brouard  13652:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  13653:   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  13654: 
1.136     brouard  13655:   /* Reads data from file datafile */
                   13656:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13657:     goto end;
                   13658: 
                   13659:   /* Calculation of the number of parameters from char model */
1.234     brouard  13660:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  13661:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13662:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13663:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13664:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  13665:   */
                   13666:   
                   13667:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13668:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  13669:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  13670:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  13671:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13672:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13673:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  13674:   TvarF=ivector(1,NCOVMAX); /*  */
                   13675:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13676:   TvarV=ivector(1,NCOVMAX); /*  */
                   13677:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13678:   TvarA=ivector(1,NCOVMAX); /*  */
                   13679:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13680:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13681:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13682:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13683:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13684:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13685:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13686:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13687:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  13688:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13689:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  13690:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13691:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13692:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13693:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  13694: 
1.230     brouard  13695:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  13696:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13697:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13698:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13699:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  13700:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13701:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13702: 
1.137     brouard  13703:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13704:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13705:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13706:   */
                   13707:   /* For model-covariate k tells which data-covariate to use but
                   13708:     because this model-covariate is a construction we invent a new column
                   13709:     ncovcol + k1
                   13710:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13711:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13712:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13713:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13714:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13715:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13716:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13717:   */
1.145     brouard  13718:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13719:   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  13720:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13721:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  13722:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  13723:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13724:                         4 covariates (3 plus signs)
                   13725:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13726:                           */  
                   13727:   for(i=1;i<NCOVMAX;i++)
                   13728:     Tage[i]=0;
1.230     brouard  13729:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13730:                                * individual dummy, fixed or varying:
                   13731:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13732:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13733:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13734:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13735:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13736:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13737:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13738:                                * individual quantitative, fixed or varying:
                   13739:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13740:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13741:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  13742: 
                   13743: /* Probably useless zeroes */
                   13744:   for(i=1;i<NCOVMAX;i++){
                   13745:     DummyV[i]=0;
                   13746:     FixedV[i]=0;
                   13747:   }
                   13748: 
                   13749:   for(i=1; i <=ncovcol;i++){
                   13750:     DummyV[i]=0;
                   13751:     FixedV[i]=0;
                   13752:   }
                   13753:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   13754:     DummyV[i]=1;
                   13755:     FixedV[i]=0;
                   13756:   }
                   13757:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   13758:     DummyV[i]=0;
                   13759:     FixedV[i]=1;
                   13760:   }
                   13761:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13762:     DummyV[i]=1;
                   13763:     FixedV[i]=1;
                   13764:   }
                   13765:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   13766:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   13767:     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]);
                   13768:   }
                   13769: 
                   13770: 
                   13771: 
1.186     brouard  13772: /* Main decodemodel */
                   13773: 
1.187     brouard  13774: 
1.223     brouard  13775:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13776:     goto end;
                   13777: 
1.137     brouard  13778:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13779:     nbwarn++;
                   13780:     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); 
                   13781:     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); 
                   13782:   }
1.136     brouard  13783:     /*  if(mle==1){*/
1.137     brouard  13784:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13785:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13786:   }
                   13787: 
                   13788:     /*-calculation of age at interview from date of interview and age at death -*/
                   13789:   agev=matrix(1,maxwav,1,imx);
                   13790: 
                   13791:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13792:     goto end;
                   13793: 
1.126     brouard  13794: 
1.136     brouard  13795:   agegomp=(int)agemin;
1.290     brouard  13796:   free_vector(moisnais,firstobs,lastobs);
                   13797:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13798:   /* free_matrix(mint,1,maxwav,1,n);
                   13799:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13800:   /* free_vector(moisdc,1,n); */
                   13801:   /* free_vector(andc,1,n); */
1.145     brouard  13802:   /* */
                   13803:   
1.126     brouard  13804:   wav=ivector(1,imx);
1.214     brouard  13805:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13806:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13807:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13808:   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.*/
                   13809:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13810:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13811:    
                   13812:   /* Concatenates waves */
1.214     brouard  13813:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13814:      Death is a valid wave (if date is known).
                   13815:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13816:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13817:      and mw[mi+1][i]. dh depends on stepm.
                   13818:   */
                   13819: 
1.126     brouard  13820:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13821:   /* Concatenates waves */
1.145     brouard  13822:  
1.290     brouard  13823:   free_vector(moisdc,firstobs,lastobs);
                   13824:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13825: 
1.126     brouard  13826:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13827:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13828:   ncodemax[1]=1;
1.145     brouard  13829:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13830:   cptcoveff=0;
1.220     brouard  13831:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13832:     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  13833:   }
                   13834:   
                   13835:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13836:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13837:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13838:     invalidvarcomb[i]=0;
                   13839:   
1.211     brouard  13840:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13841:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13842:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13843:   
1.200     brouard  13844:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13845:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13846:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13847:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13848:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13849:    * (currently 0 or 1) in the data.
                   13850:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13851:    * corresponding modality (h,j).
                   13852:    */
                   13853: 
1.145     brouard  13854:   h=0;
                   13855:   /*if (cptcovn > 0) */
1.126     brouard  13856:   m=pow(2,cptcoveff);
                   13857:  
1.144     brouard  13858:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13859:           * For k=4 covariates, h goes from 1 to m=2**k
                   13860:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13861:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13862:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13863:           *______________________________   *______________________
                   13864:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13865:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13866:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13867:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13868:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13869:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13870:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13871:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13872:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13873:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13874:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13875:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13876:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13877:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13878:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13879:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13880:           */                                     
1.212     brouard  13881:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13882:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13883:      * and the value of each covariate?
                   13884:      * V1=1, V2=1, V3=2, V4=1 ?
                   13885:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13886:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13887:      * In order to get the real value in the data, we use nbcode
                   13888:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13889:      * We are keeping this crazy system in order to be able (in the future?) 
                   13890:      * to have more than 2 values (0 or 1) for a covariate.
                   13891:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13892:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13893:      *              bbbbbbbb
                   13894:      *              76543210     
                   13895:      *   h-1        00000101 (6-1=5)
1.219     brouard  13896:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13897:      *           &
                   13898:      *     1        00000001 (1)
1.219     brouard  13899:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13900:      *          +1= 00000001 =1 
1.211     brouard  13901:      *
                   13902:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13903:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13904:      *    >>k'            11
                   13905:      *          &   00000001
                   13906:      *            = 00000001
                   13907:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13908:      * Reverse h=6 and m=16?
                   13909:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13910:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13911:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13912:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13913:      * V3=decodtabm(14,3,2**4)=2
                   13914:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13915:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13916:      *          &1 000000001
                   13917:      *           = 000000001
                   13918:      *         +1= 000000010 =2
                   13919:      *                  2211
                   13920:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13921:      *                  V3=2
1.220     brouard  13922:                 * codtabm and decodtabm are identical
1.211     brouard  13923:      */
                   13924: 
1.145     brouard  13925: 
                   13926:  free_ivector(Ndum,-1,NCOVMAX);
                   13927: 
                   13928: 
1.126     brouard  13929:     
1.186     brouard  13930:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13931:   strcpy(optionfilegnuplot,optionfilefiname);
                   13932:   if(mle==-3)
1.201     brouard  13933:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13934:   strcat(optionfilegnuplot,".gp");
                   13935: 
                   13936:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13937:     printf("Problem with file %s",optionfilegnuplot);
                   13938:   }
                   13939:   else{
1.204     brouard  13940:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13941:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13942:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13943:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13944:   }
                   13945:   /*  fclose(ficgp);*/
1.186     brouard  13946: 
                   13947: 
                   13948:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13949: 
                   13950:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13951:   if(mle==-3)
1.201     brouard  13952:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13953:   strcat(optionfilehtm,".htm");
                   13954:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13955:     printf("Problem with %s \n",optionfilehtm);
                   13956:     exit(0);
1.126     brouard  13957:   }
                   13958: 
                   13959:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13960:   strcat(optionfilehtmcov,"-cov.htm");
                   13961:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13962:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13963:   }
                   13964:   else{
                   13965:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13966: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13967: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13968:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13969:   }
                   13970: 
1.335     brouard  13971:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13972: <title>IMaCh %s</title></head>\n\
                   13973:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13974: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13975: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13976: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13977: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13978:   
                   13979:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13980: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13981: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13982: 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  13983: \n\
                   13984: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13985:  <ul><li><h4>Parameter files</h4>\n\
                   13986:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13987:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13988:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13989:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13990:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13991:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13992:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13993:          fileres,fileres,\
                   13994:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13995:   fflush(fichtm);
                   13996: 
                   13997:   strcpy(pathr,path);
                   13998:   strcat(pathr,optionfilefiname);
1.184     brouard  13999: #ifdef WIN32
                   14000:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14001: #else
1.126     brouard  14002:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  14003: #endif
                   14004:          
1.126     brouard  14005:   
1.220     brouard  14006:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14007:                 and for any valid combination of covariates
1.126     brouard  14008:      and prints on file fileres'p'. */
1.251     brouard  14009:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  14010:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  14011: 
                   14012:   fprintf(fichtm,"\n");
1.286     brouard  14013:   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  14014:          ftol, stepm);
                   14015:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14016:   ncurrv=1;
                   14017:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14018:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14019:   ncurrv=i;
                   14020:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14021:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  14022:   ncurrv=i;
                   14023:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  14024:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  14025:   ncurrv=i;
                   14026:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14027:   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", \
                   14028:           nlstate, ndeath, maxwav, mle, weightopt);
                   14029: 
                   14030:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14031: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14032: 
                   14033:   
1.317     brouard  14034:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  14035: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14036: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  14037:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  14038:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  14039:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14040:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14041:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14042:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  14043: 
1.126     brouard  14044:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14045:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14046:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14047: 
                   14048:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  14049:   /* For mortality only */
1.126     brouard  14050:   if (mle==-3){
1.136     brouard  14051:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  14052:     for(i=1;i<=NDIM;i++)
                   14053:       for(j=1;j<=NDIM;j++)
                   14054:        ximort[i][j]=0.;
1.186     brouard  14055:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  14056:     cens=ivector(firstobs,lastobs);
                   14057:     ageexmed=vector(firstobs,lastobs);
                   14058:     agecens=vector(firstobs,lastobs);
                   14059:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  14060:                
1.126     brouard  14061:     for (i=1; i<=imx; i++){
                   14062:       dcwave[i]=-1;
                   14063:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  14064:        if (s[m][i]>nlstate) {
                   14065:          dcwave[i]=m;
                   14066:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14067:          break;
                   14068:        }
1.126     brouard  14069:     }
1.226     brouard  14070:     
1.126     brouard  14071:     for (i=1; i<=imx; i++) {
                   14072:       if (wav[i]>0){
1.226     brouard  14073:        ageexmed[i]=agev[mw[1][i]][i];
                   14074:        j=wav[i];
                   14075:        agecens[i]=1.; 
                   14076:        
                   14077:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14078:          agecens[i]=agev[mw[j][i]][i];
                   14079:          cens[i]= 1;
                   14080:        }else if (ageexmed[i]< 1) 
                   14081:          cens[i]= -1;
                   14082:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14083:          cens[i]=0 ;
1.126     brouard  14084:       }
                   14085:       else cens[i]=-1;
                   14086:     }
                   14087:     
                   14088:     for (i=1;i<=NDIM;i++) {
                   14089:       for (j=1;j<=NDIM;j++)
1.226     brouard  14090:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  14091:     }
                   14092:     
1.302     brouard  14093:     p[1]=0.0268; p[NDIM]=0.083;
                   14094:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  14095:     
                   14096:     
1.136     brouard  14097: #ifdef GSL
                   14098:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  14099: #else
1.126     brouard  14100:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  14101: #endif
1.201     brouard  14102:     strcpy(filerespow,"POW-MORT_"); 
                   14103:     strcat(filerespow,fileresu);
1.126     brouard  14104:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14105:       printf("Problem with resultfile: %s\n", filerespow);
                   14106:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14107:     }
1.136     brouard  14108: #ifdef GSL
                   14109:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  14110: #else
1.126     brouard  14111:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  14112: #endif
1.126     brouard  14113:     /*  for (i=1;i<=nlstate;i++)
                   14114:        for(j=1;j<=nlstate+ndeath;j++)
                   14115:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14116:     */
                   14117:     fprintf(ficrespow,"\n");
1.136     brouard  14118: #ifdef GSL
                   14119:     /* gsl starts here */ 
                   14120:     T = gsl_multimin_fminimizer_nmsimplex;
                   14121:     gsl_multimin_fminimizer *sfm = NULL;
                   14122:     gsl_vector *ss, *x;
                   14123:     gsl_multimin_function minex_func;
                   14124: 
                   14125:     /* Initial vertex size vector */
                   14126:     ss = gsl_vector_alloc (NDIM);
                   14127:     
                   14128:     if (ss == NULL){
                   14129:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14130:     }
                   14131:     /* Set all step sizes to 1 */
                   14132:     gsl_vector_set_all (ss, 0.001);
                   14133: 
                   14134:     /* Starting point */
1.126     brouard  14135:     
1.136     brouard  14136:     x = gsl_vector_alloc (NDIM);
                   14137:     
                   14138:     if (x == NULL){
                   14139:       gsl_vector_free(ss);
                   14140:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14141:     }
                   14142:   
                   14143:     /* Initialize method and iterate */
                   14144:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  14145:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14146:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  14147:     gsl_vector_set(x, 0, p[1]);
                   14148:     gsl_vector_set(x, 1, p[2]);
                   14149: 
                   14150:     minex_func.f = &gompertz_f;
                   14151:     minex_func.n = NDIM;
                   14152:     minex_func.params = (void *)&p; /* ??? */
                   14153:     
                   14154:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14155:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14156:     
                   14157:     printf("Iterations beginning .....\n\n");
                   14158:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14159: 
                   14160:     iteri=0;
                   14161:     while (rval == GSL_CONTINUE){
                   14162:       iteri++;
                   14163:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14164:       
                   14165:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14166:       fflush(0);
                   14167:       
                   14168:       if (status) 
                   14169:         break;
                   14170:       
                   14171:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14172:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14173:       
                   14174:       if (rval == GSL_SUCCESS)
                   14175:         printf ("converged to a local maximum at\n");
                   14176:       
                   14177:       printf("%5d ", iteri);
                   14178:       for (it = 0; it < NDIM; it++){
                   14179:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14180:       }
                   14181:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14182:     }
                   14183:     
                   14184:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14185:     
                   14186:     gsl_vector_free(x); /* initial values */
                   14187:     gsl_vector_free(ss); /* inital step size */
                   14188:     for (it=0; it<NDIM; it++){
                   14189:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14190:       fprintf(ficrespow," %.12lf", p[it]);
                   14191:     }
                   14192:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14193: #endif
                   14194: #ifdef POWELL
                   14195:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14196: #endif  
1.126     brouard  14197:     fclose(ficrespow);
                   14198:     
1.203     brouard  14199:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  14200: 
                   14201:     for(i=1; i <=NDIM; i++)
                   14202:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  14203:                                matcov[i][j]=matcov[j][i];
1.126     brouard  14204:     
                   14205:     printf("\nCovariance matrix\n ");
1.203     brouard  14206:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  14207:     for(i=1; i <=NDIM; i++) {
                   14208:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  14209:                                printf("%f ",matcov[i][j]);
                   14210:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  14211:       }
1.203     brouard  14212:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  14213:     }
                   14214:     
                   14215:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  14216:     for (i=1;i<=NDIM;i++) {
1.126     brouard  14217:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  14218:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14219:     }
1.302     brouard  14220:     lsurv=vector(agegomp,AGESUP);
                   14221:     lpop=vector(agegomp,AGESUP);
                   14222:     tpop=vector(agegomp,AGESUP);
1.126     brouard  14223:     lsurv[agegomp]=100000;
                   14224:     
                   14225:     for (k=agegomp;k<=AGESUP;k++) {
                   14226:       agemortsup=k;
                   14227:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14228:     }
                   14229:     
                   14230:     for (k=agegomp;k<agemortsup;k++)
                   14231:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14232:     
                   14233:     for (k=agegomp;k<agemortsup;k++){
                   14234:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14235:       sumlpop=sumlpop+lpop[k];
                   14236:     }
                   14237:     
                   14238:     tpop[agegomp]=sumlpop;
                   14239:     for (k=agegomp;k<(agemortsup-3);k++){
                   14240:       /*  tpop[k+1]=2;*/
                   14241:       tpop[k+1]=tpop[k]-lpop[k];
                   14242:     }
                   14243:     
                   14244:     
                   14245:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14246:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14247:       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]);
                   14248:     
                   14249:     
                   14250:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  14251:                ageminpar=50;
                   14252:                agemaxpar=100;
1.194     brouard  14253:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14254:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14255: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14256: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14257:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14258: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14259: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14260:     }else{
                   14261:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14262:                        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  14263:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  14264:                }
1.201     brouard  14265:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  14266:                     stepm, weightopt,\
                   14267:                     model,imx,p,matcov,agemortsup);
                   14268:     
1.302     brouard  14269:     free_vector(lsurv,agegomp,AGESUP);
                   14270:     free_vector(lpop,agegomp,AGESUP);
                   14271:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  14272:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  14273:     free_ivector(dcwave,firstobs,lastobs);
                   14274:     free_vector(agecens,firstobs,lastobs);
                   14275:     free_vector(ageexmed,firstobs,lastobs);
                   14276:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  14277: #ifdef GSL
1.136     brouard  14278: #endif
1.186     brouard  14279:   } /* Endof if mle==-3 mortality only */
1.205     brouard  14280:   /* Standard  */
                   14281:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14282:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14283:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  14284:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  14285:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14286:     for (k=1; k<=npar;k++)
                   14287:       printf(" %d %8.5f",k,p[k]);
                   14288:     printf("\n");
1.205     brouard  14289:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14290:       /* mlikeli uses func not funcone */
1.247     brouard  14291:       /* for(i=1;i<nlstate;i++){ */
                   14292:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14293:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14294:       /* } */
1.205     brouard  14295:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14296:     }
                   14297:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14298:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14299:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14300:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14301:     }
                   14302:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  14303:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14304:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  14305:           /* exit(0); */
1.126     brouard  14306:     for (k=1; k<=npar;k++)
                   14307:       printf(" %d %8.5f",k,p[k]);
                   14308:     printf("\n");
                   14309:     
                   14310:     /*--------- results files --------------*/
1.283     brouard  14311:     /* 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  14312:     
                   14313:     
                   14314:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14315:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  14316:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  14317: 
                   14318:     printf("#model=  1      +     age ");
                   14319:     fprintf(ficres,"#model=  1      +     age ");
                   14320:     fprintf(ficlog,"#model=  1      +     age ");
                   14321:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14322: </ul>", model);
                   14323: 
                   14324:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14325:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14326:     if(nagesqr==1){
                   14327:       printf("  + age*age  ");
                   14328:       fprintf(ficres,"  + age*age  ");
                   14329:       fprintf(ficlog,"  + age*age  ");
                   14330:       fprintf(fichtm, "<th>+ age*age</th>");
                   14331:     }
                   14332:     for(j=1;j <=ncovmodel-2;j++){
                   14333:       if(Typevar[j]==0) {
                   14334:        printf("  +      V%d  ",Tvar[j]);
                   14335:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14336:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14337:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14338:       }else if(Typevar[j]==1) {
                   14339:        printf("  +    V%d*age ",Tvar[j]);
                   14340:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14341:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14342:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14343:       }else if(Typevar[j]==2) {
                   14344:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14345:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14346:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14347:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14348:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14349:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14350:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14351:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14352:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14353:       }
                   14354:     }
                   14355:     printf("\n");
                   14356:     fprintf(ficres,"\n");
                   14357:     fprintf(ficlog,"\n");
                   14358:     fprintf(fichtm, "</tr>");
                   14359:     fprintf(fichtm, "\n");
                   14360:     
                   14361:     
1.126     brouard  14362:     for(i=1,jk=1; i <=nlstate; i++){
                   14363:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  14364:        if (k != i) {
1.319     brouard  14365:          fprintf(fichtm, "<tr>");
1.225     brouard  14366:          printf("%d%d ",i,k);
                   14367:          fprintf(ficlog,"%d%d ",i,k);
                   14368:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  14369:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14370:          for(j=1; j <=ncovmodel; j++){
                   14371:            printf("%12.7f ",p[jk]);
                   14372:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14373:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  14374:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  14375:            jk++; 
                   14376:          }
                   14377:          printf("\n");
                   14378:          fprintf(ficlog,"\n");
                   14379:          fprintf(ficres,"\n");
1.319     brouard  14380:          fprintf(fichtm, "</tr>\n");
1.225     brouard  14381:        }
1.126     brouard  14382:       }
                   14383:     }
1.319     brouard  14384:     /* fprintf(fichtm,"</tr>\n"); */
                   14385:     fprintf(fichtm,"</table>\n");
                   14386:     fprintf(fichtm, "\n");
                   14387: 
1.203     brouard  14388:     if(mle != 0){
                   14389:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  14390:       ftolhess=ftol; /* Usually correct */
1.203     brouard  14391:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14392:       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");
                   14393:       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  14394:       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  14395:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14396:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14397:       if(nagesqr==1){
                   14398:        printf("  + age*age  ");
                   14399:        fprintf(ficres,"  + age*age  ");
                   14400:        fprintf(ficlog,"  + age*age  ");
                   14401:        fprintf(fichtm, "<th>+ age*age</th>");
                   14402:       }
                   14403:       for(j=1;j <=ncovmodel-2;j++){
                   14404:        if(Typevar[j]==0) {
                   14405:          printf("  +      V%d  ",Tvar[j]);
                   14406:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14407:        }else if(Typevar[j]==1) {
                   14408:          printf("  +    V%d*age ",Tvar[j]);
                   14409:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14410:        }else if(Typevar[j]==2) {
                   14411:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  14412:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14413:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  14414:        }
                   14415:       }
                   14416:       fprintf(fichtm, "</tr>\n");
                   14417:  
1.203     brouard  14418:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  14419:        for(k=1; k <=(nlstate+ndeath); k++){
                   14420:          if (k != i) {
1.319     brouard  14421:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  14422:            printf("%d%d ",i,k);
                   14423:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  14424:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  14425:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  14426:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  14427:              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]));
                   14428:              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  14429:              if(fabs(wald) > 1.96){
1.321     brouard  14430:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  14431:              }else{
                   14432:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14433:              }
1.324     brouard  14434:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  14435:              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  14436:              jk++; 
                   14437:            }
                   14438:            printf("\n");
                   14439:            fprintf(ficlog,"\n");
1.319     brouard  14440:            fprintf(fichtm, "</tr>\n");
1.225     brouard  14441:          }
                   14442:        }
1.193     brouard  14443:       }
1.203     brouard  14444:     } /* end of hesscov and Wald tests */
1.319     brouard  14445:     fprintf(fichtm,"</table>\n");
1.225     brouard  14446:     
1.203     brouard  14447:     /*  */
1.126     brouard  14448:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14449:     printf("# Scales (for hessian or gradient estimation)\n");
                   14450:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14451:     for(i=1,jk=1; i <=nlstate; i++){
                   14452:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  14453:        if (j!=i) {
                   14454:          fprintf(ficres,"%1d%1d",i,j);
                   14455:          printf("%1d%1d",i,j);
                   14456:          fprintf(ficlog,"%1d%1d",i,j);
                   14457:          for(k=1; k<=ncovmodel;k++){
                   14458:            printf(" %.5e",delti[jk]);
                   14459:            fprintf(ficlog," %.5e",delti[jk]);
                   14460:            fprintf(ficres," %.5e",delti[jk]);
                   14461:            jk++;
                   14462:          }
                   14463:          printf("\n");
                   14464:          fprintf(ficlog,"\n");
                   14465:          fprintf(ficres,"\n");
                   14466:        }
1.126     brouard  14467:       }
                   14468:     }
                   14469:     
                   14470:     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  14471:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  14472:       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");
                   14473:     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");
                   14474:     /* # 121 Var(a12)\n\ */
                   14475:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14476:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14477:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14478:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14479:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14480:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14481:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14482:     
                   14483:     
                   14484:     /* Just to have a covariance matrix which will be more understandable
                   14485:        even is we still don't want to manage dictionary of variables
                   14486:     */
                   14487:     for(itimes=1;itimes<=2;itimes++){
                   14488:       jj=0;
                   14489:       for(i=1; i <=nlstate; i++){
1.225     brouard  14490:        for(j=1; j <=nlstate+ndeath; j++){
                   14491:          if(j==i) continue;
                   14492:          for(k=1; k<=ncovmodel;k++){
                   14493:            jj++;
                   14494:            ca[0]= k+'a'-1;ca[1]='\0';
                   14495:            if(itimes==1){
                   14496:              if(mle>=1)
                   14497:                printf("#%1d%1d%d",i,j,k);
                   14498:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14499:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14500:            }else{
                   14501:              if(mle>=1)
                   14502:                printf("%1d%1d%d",i,j,k);
                   14503:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14504:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14505:            }
                   14506:            ll=0;
                   14507:            for(li=1;li <=nlstate; li++){
                   14508:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14509:                if(lj==li) continue;
                   14510:                for(lk=1;lk<=ncovmodel;lk++){
                   14511:                  ll++;
                   14512:                  if(ll<=jj){
                   14513:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14514:                    if(ll<jj){
                   14515:                      if(itimes==1){
                   14516:                        if(mle>=1)
                   14517:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14518:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14519:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14520:                      }else{
                   14521:                        if(mle>=1)
                   14522:                          printf(" %.5e",matcov[jj][ll]); 
                   14523:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14524:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14525:                      }
                   14526:                    }else{
                   14527:                      if(itimes==1){
                   14528:                        if(mle>=1)
                   14529:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14530:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14531:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14532:                      }else{
                   14533:                        if(mle>=1)
                   14534:                          printf(" %.7e",matcov[jj][ll]); 
                   14535:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14536:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14537:                      }
                   14538:                    }
                   14539:                  }
                   14540:                } /* end lk */
                   14541:              } /* end lj */
                   14542:            } /* end li */
                   14543:            if(mle>=1)
                   14544:              printf("\n");
                   14545:            fprintf(ficlog,"\n");
                   14546:            fprintf(ficres,"\n");
                   14547:            numlinepar++;
                   14548:          } /* end k*/
                   14549:        } /*end j */
1.126     brouard  14550:       } /* end i */
                   14551:     } /* end itimes */
                   14552:     
                   14553:     fflush(ficlog);
                   14554:     fflush(ficres);
1.225     brouard  14555:     while(fgets(line, MAXLINE, ficpar)) {
                   14556:       /* If line starts with a # it is a comment */
                   14557:       if (line[0] == '#') {
                   14558:        numlinepar++;
                   14559:        fputs(line,stdout);
                   14560:        fputs(line,ficparo);
                   14561:        fputs(line,ficlog);
1.299     brouard  14562:        fputs(line,ficres);
1.225     brouard  14563:        continue;
                   14564:       }else
                   14565:        break;
                   14566:     }
                   14567:     
1.209     brouard  14568:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14569:     /*   ungetc(c,ficpar); */
                   14570:     /*   fgets(line, MAXLINE, ficpar); */
                   14571:     /*   fputs(line,stdout); */
                   14572:     /*   fputs(line,ficparo); */
                   14573:     /* } */
                   14574:     /* ungetc(c,ficpar); */
1.126     brouard  14575:     
                   14576:     estepm=0;
1.209     brouard  14577:     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  14578:       
                   14579:       if (num_filled != 6) {
                   14580:        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);
                   14581:        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);
                   14582:        goto end;
                   14583:       }
                   14584:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14585:     }
                   14586:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14587:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14588:     
1.209     brouard  14589:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  14590:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14591:     if (fage <= 2) {
                   14592:       bage = ageminpar;
                   14593:       fage = agemaxpar;
                   14594:     }
                   14595:     
                   14596:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  14597:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14598:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  14599:                
1.186     brouard  14600:     /* Other stuffs, more or less useful */    
1.254     brouard  14601:     while(fgets(line, MAXLINE, ficpar)) {
                   14602:       /* If line starts with a # it is a comment */
                   14603:       if (line[0] == '#') {
                   14604:        numlinepar++;
                   14605:        fputs(line,stdout);
                   14606:        fputs(line,ficparo);
                   14607:        fputs(line,ficlog);
1.299     brouard  14608:        fputs(line,ficres);
1.254     brouard  14609:        continue;
                   14610:       }else
                   14611:        break;
                   14612:     }
                   14613: 
                   14614:     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){
                   14615:       
                   14616:       if (num_filled != 7) {
                   14617:        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);
                   14618:        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);
                   14619:        goto end;
                   14620:       }
                   14621:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14622:       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);
                   14623:       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);
                   14624:       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  14625:     }
1.254     brouard  14626: 
                   14627:     while(fgets(line, MAXLINE, ficpar)) {
                   14628:       /* If line starts with a # it is a comment */
                   14629:       if (line[0] == '#') {
                   14630:        numlinepar++;
                   14631:        fputs(line,stdout);
                   14632:        fputs(line,ficparo);
                   14633:        fputs(line,ficlog);
1.299     brouard  14634:        fputs(line,ficres);
1.254     brouard  14635:        continue;
                   14636:       }else
                   14637:        break;
1.126     brouard  14638:     }
                   14639:     
                   14640:     
                   14641:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14642:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14643:     
1.254     brouard  14644:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14645:       if (num_filled != 1) {
                   14646:        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);
                   14647:        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);
                   14648:        goto end;
                   14649:       }
                   14650:       printf("pop_based=%d\n",popbased);
                   14651:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14652:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14653:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14654:     }
                   14655:      
1.258     brouard  14656:     /* Results */
1.332     brouard  14657:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14658:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14659:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  14660:     endishere=0;
1.258     brouard  14661:     nresult=0;
1.308     brouard  14662:     parameterline=0;
1.258     brouard  14663:     do{
                   14664:       if(!fgets(line, MAXLINE, ficpar)){
                   14665:        endishere=1;
1.308     brouard  14666:        parameterline=15;
1.258     brouard  14667:       }else if (line[0] == '#') {
                   14668:        /* If line starts with a # it is a comment */
1.254     brouard  14669:        numlinepar++;
                   14670:        fputs(line,stdout);
                   14671:        fputs(line,ficparo);
                   14672:        fputs(line,ficlog);
1.299     brouard  14673:        fputs(line,ficres);
1.254     brouard  14674:        continue;
1.258     brouard  14675:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14676:        parameterline=11;
1.296     brouard  14677:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  14678:        parameterline=12;
1.307     brouard  14679:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  14680:        parameterline=13;
1.307     brouard  14681:       }
1.258     brouard  14682:       else{
                   14683:        parameterline=14;
1.254     brouard  14684:       }
1.308     brouard  14685:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  14686:       case 11:
1.296     brouard  14687:        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)){
                   14688:                  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  14689:          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);
                   14690:          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);
                   14691:          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);
                   14692:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  14693:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14694:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  14695:           prvforecast = 1;
                   14696:        } 
                   14697:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  14698:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14699:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14700:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  14701:           prvforecast = 2;
                   14702:        }
                   14703:        else {
                   14704:          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);
                   14705:          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);
                   14706:          goto end;
1.258     brouard  14707:        }
1.254     brouard  14708:        break;
1.258     brouard  14709:       case 12:
1.296     brouard  14710:        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)){
                   14711:           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);
                   14712:          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);
                   14713:          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);
                   14714:          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);
                   14715:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  14716:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14717:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  14718:           prvbackcast = 1;
                   14719:        } 
                   14720:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  14721:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14722:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   14723:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  14724:           prvbackcast = 2;
                   14725:        }
                   14726:        else {
                   14727:          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);
                   14728:          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);
                   14729:          goto end;
1.258     brouard  14730:        }
1.230     brouard  14731:        break;
1.258     brouard  14732:       case 13:
1.332     brouard  14733:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  14734:        nresult++; /* Sum of resultlines */
1.342     brouard  14735:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  14736:        /* removefirstspace(&resultlineori); */
                   14737:        
                   14738:        if(strstr(resultlineori,"v") !=0){
                   14739:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14740:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14741:          return 1;
                   14742:        }
                   14743:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14744:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14745:        if(nresult > MAXRESULTLINESPONE-1){
                   14746:          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);
                   14747:          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  14748:          goto end;
                   14749:        }
1.332     brouard  14750:        
1.310     brouard  14751:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14752:          fprintf(ficparo,"result: %s\n",resultline);
                   14753:          fprintf(ficres,"result: %s\n",resultline);
                   14754:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14755:        } else
                   14756:          goto end;
1.307     brouard  14757:        break;
                   14758:       case 14:
                   14759:        printf("Error: Unknown command '%s'\n",line);
                   14760:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14761:        if(line[0] == ' ' || line[0] == '\n'){
                   14762:          printf("It should not be an empty line '%s'\n",line);
                   14763:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14764:        }         
1.307     brouard  14765:        if(ncovmodel >=2 && nresult==0 ){
                   14766:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14767:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14768:        }
1.307     brouard  14769:        /* goto end; */
                   14770:        break;
1.308     brouard  14771:       case 15:
                   14772:        printf("End of resultlines.\n");
                   14773:        fprintf(ficlog,"End of resultlines.\n");
                   14774:        break;
                   14775:       default: /* parameterline =0 */
1.307     brouard  14776:        nresult=1;
                   14777:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14778:       } /* End switch parameterline */
                   14779:     }while(endishere==0); /* End do */
1.126     brouard  14780:     
1.230     brouard  14781:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14782:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14783:     
                   14784:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14785:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14786:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14787: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14788: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14789:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14790: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14791: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14792:     }else{
1.270     brouard  14793:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14794:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14795:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14796:       if(prvforecast==1){
                   14797:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14798:         jprojd=jproj1;
                   14799:         mprojd=mproj1;
                   14800:         anprojd=anproj1;
                   14801:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14802:         jprojf=jproj2;
                   14803:         mprojf=mproj2;
                   14804:         anprojf=anproj2;
                   14805:       } else if(prvforecast == 2){
                   14806:         dateprojd=dateintmean;
                   14807:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14808:         dateprojf=dateintmean+yrfproj;
                   14809:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14810:       }
                   14811:       if(prvbackcast==1){
                   14812:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14813:         jbackd=jback1;
                   14814:         mbackd=mback1;
                   14815:         anbackd=anback1;
                   14816:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14817:         jbackf=jback2;
                   14818:         mbackf=mback2;
                   14819:         anbackf=anback2;
                   14820:       } else if(prvbackcast == 2){
                   14821:         datebackd=dateintmean;
                   14822:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14823:         datebackf=dateintmean-yrbproj;
                   14824:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14825:       }
                   14826:       
1.350     brouard  14827:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  14828:     }
                   14829:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14830:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14831:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14832:                
1.225     brouard  14833:     /*------------ free_vector  -------------*/
                   14834:     /*  chdir(path); */
1.220     brouard  14835:                
1.215     brouard  14836:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14837:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14838:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14839:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14840:     free_lvector(num,firstobs,lastobs);
                   14841:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14842:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14843:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14844:     fclose(ficparo);
                   14845:     fclose(ficres);
1.220     brouard  14846:                
                   14847:                
1.186     brouard  14848:     /* Other results (useful)*/
1.220     brouard  14849:                
                   14850:                
1.126     brouard  14851:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14852:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14853:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14854:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14855:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14856:     fclose(ficrespl);
                   14857: 
                   14858:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14859:     /*#include "hpijx.h"*/
1.332     brouard  14860:     /** 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?*/
                   14861:     /* calls hpxij with combination k */
1.180     brouard  14862:     hPijx(p, bage, fage);
1.145     brouard  14863:     fclose(ficrespij);
1.227     brouard  14864:     
1.220     brouard  14865:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14866:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14867:     k=1;
1.126     brouard  14868:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14869:     
1.269     brouard  14870:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14871:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14872:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14873:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14874:        for(k=1;k<=ncovcombmax;k++)
                   14875:          probs[i][j][k]=0.;
1.269     brouard  14876:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14877:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14878:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14879:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14880:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14881:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14882:          for(k=1;k<=ncovcombmax;k++)
                   14883:            mobaverages[i][j][k]=0.;
1.219     brouard  14884:       mobaverage=mobaverages;
                   14885:       if (mobilav!=0) {
1.235     brouard  14886:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14887:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14888:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14889:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14890:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14891:        }
1.269     brouard  14892:       } else if (mobilavproj !=0) {
1.235     brouard  14893:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14894:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14895:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14896:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14897:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14898:        }
1.269     brouard  14899:       }else{
                   14900:        printf("Internal error moving average\n");
                   14901:        fflush(stdout);
                   14902:        exit(1);
1.219     brouard  14903:       }
                   14904:     }/* end if moving average */
1.227     brouard  14905:     
1.126     brouard  14906:     /*---------- Forecasting ------------------*/
1.296     brouard  14907:     if(prevfcast==1){ 
                   14908:       /*   /\*    if(stepm ==1){*\/ */
                   14909:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14910:       /*This done previously after freqsummary.*/
                   14911:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14912:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14913:       
                   14914:       /* } else if (prvforecast==2){ */
                   14915:       /*   /\*    if(stepm ==1){*\/ */
                   14916:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14917:       /* } */
                   14918:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14919:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14920:     }
1.269     brouard  14921: 
1.296     brouard  14922:     /* Prevbcasting */
                   14923:     if(prevbcast==1){
1.219     brouard  14924:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14925:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14926:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14927: 
                   14928:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14929: 
                   14930:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14931: 
1.219     brouard  14932:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14933:       fclose(ficresplb);
                   14934: 
1.222     brouard  14935:       hBijx(p, bage, fage, mobaverage);
                   14936:       fclose(ficrespijb);
1.219     brouard  14937: 
1.296     brouard  14938:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14939:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14940:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14941:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14942:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14943:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14944: 
                   14945:       
1.269     brouard  14946:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14947: 
                   14948:       
1.269     brouard  14949:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14950:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14951:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14952:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14953:     }    /* end  Prevbcasting */
1.268     brouard  14954:  
1.186     brouard  14955:  
                   14956:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14957: 
1.215     brouard  14958:     free_ivector(wav,1,imx);
                   14959:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14960:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14961:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14962:                
                   14963:                
1.127     brouard  14964:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14965:                
1.201     brouard  14966:     strcpy(filerese,"E_");
                   14967:     strcat(filerese,fileresu);
1.126     brouard  14968:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14969:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14970:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14971:     }
1.208     brouard  14972:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14973:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14974: 
                   14975:     pstamp(ficreseij);
1.219     brouard  14976:                
1.351     brouard  14977:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   14978:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  14979:     
1.351     brouard  14980:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14981:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14982:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   14983:       /*       continue; */
1.219     brouard  14984:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14985:       printf("\n#****** ");
1.351     brouard  14986:       for(j=1;j<=cptcovs;j++){
                   14987:       /* for(j=1;j<=cptcoveff;j++) { */
                   14988:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14989:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14990:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14991:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  14992:       }
                   14993:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14994:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14995:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14996:       }
                   14997:       fprintf(ficreseij,"******\n");
1.235     brouard  14998:       printf("******\n");
1.219     brouard  14999:       
                   15000:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15001:       oldm=oldms;savm=savms;
1.330     brouard  15002:       /* 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  15003:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  15004:       
1.219     brouard  15005:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  15006:     }
                   15007:     fclose(ficreseij);
1.208     brouard  15008:     printf("done evsij\n");fflush(stdout);
                   15009:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  15010: 
1.218     brouard  15011:                
1.227     brouard  15012:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  15013:     /* Should be moved in a function */                
1.201     brouard  15014:     strcpy(filerest,"T_");
                   15015:     strcat(filerest,fileresu);
1.127     brouard  15016:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15017:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15018:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15019:     }
1.208     brouard  15020:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15021:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  15022:     strcpy(fileresstde,"STDE_");
                   15023:     strcat(fileresstde,fileresu);
1.126     brouard  15024:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  15025:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15026:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  15027:     }
1.227     brouard  15028:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15029:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  15030: 
1.201     brouard  15031:     strcpy(filerescve,"CVE_");
                   15032:     strcat(filerescve,fileresu);
1.126     brouard  15033:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  15034:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15035:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  15036:     }
1.227     brouard  15037:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15038:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  15039: 
1.201     brouard  15040:     strcpy(fileresv,"V_");
                   15041:     strcat(fileresv,fileresu);
1.126     brouard  15042:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15043:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15044:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15045:     }
1.227     brouard  15046:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15047:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  15048: 
1.235     brouard  15049:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15050:     if (cptcovn < 1){i1=1;}
                   15051:     
1.334     brouard  15052:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15053:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15054:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15055:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15056:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15057:       /* */
                   15058:       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  15059:        continue;
1.350     brouard  15060:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.321     brouard  15061:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15062:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  15063:       /* It might not be a good idea to mix dummies and quantitative */
                   15064:       /* 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 *\/ */
                   15065:       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 */
                   15066:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15067:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15068:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15069:         * (V5 is quanti) V4 and V3 are dummies
                   15070:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15071:         *                                                              l=1 l=2
                   15072:         *                                                           k=1  1   1   0   0
                   15073:         *                                                           k=2  2   1   1   0
                   15074:         *                                                           k=3 [1] [2]  0   1
                   15075:         *                                                           k=4  2   2   1   1
                   15076:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15077:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15078:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15079:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15080:         */
                   15081:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15082:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15083: /* We give up with the combinations!! */
1.342     brouard  15084:        /* if(debugILK) */
                   15085:        /*   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  15086: 
                   15087:        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  15088:          /* 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] */
                   15089:          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  */
                   15090:          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  */
                   15091:          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  15092:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15093:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15094:          }else{
                   15095:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15096:          }
                   15097:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15098:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15099:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15100:          /* For each selected (single) quantitative value */
1.337     brouard  15101:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15102:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15103:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  15104:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15105:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15106:          }else{
                   15107:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15108:          }
                   15109:        }else{
                   15110:          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 */
                   15111:          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 */
                   15112:          exit(1);
                   15113:        }
1.335     brouard  15114:       } /* End loop for each variable in the resultline */
1.334     brouard  15115:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15116:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15117:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15118:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15119:       /* }      */
1.208     brouard  15120:       fprintf(ficrest,"******\n");
1.227     brouard  15121:       fprintf(ficlog,"******\n");
                   15122:       printf("******\n");
1.208     brouard  15123:       
                   15124:       fprintf(ficresstdeij,"\n#****** ");
                   15125:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  15126:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15127:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  15128:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  15129:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15130:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15131:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15132:       }
                   15133:       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  15134:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15135:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  15136:       }        
1.208     brouard  15137:       fprintf(ficresstdeij,"******\n");
                   15138:       fprintf(ficrescveij,"******\n");
                   15139:       
                   15140:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  15141:       /* pstamp(ficresvij); */
1.225     brouard  15142:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  15143:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15144:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  15145:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  15146:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  15147:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  15148:       }        
1.208     brouard  15149:       fprintf(ficresvij,"******\n");
                   15150:       
                   15151:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15152:       oldm=oldms;savm=savms;
1.235     brouard  15153:       printf(" cvevsij ");
                   15154:       fprintf(ficlog, " cvevsij ");
                   15155:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  15156:       printf(" end cvevsij \n ");
                   15157:       fprintf(ficlog, " end cvevsij \n ");
                   15158:       
                   15159:       /*
                   15160:        */
                   15161:       /* goto endfree; */
                   15162:       
                   15163:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15164:       pstamp(ficrest);
                   15165:       
1.269     brouard  15166:       epj=vector(1,nlstate+1);
1.208     brouard  15167:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  15168:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15169:        cptcod= 0; /* To be deleted */
                   15170:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15171:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  15172:        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  15173:        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 ");
                   15174:        if(vpopbased==1)
                   15175:          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);
                   15176:        else
1.288     brouard  15177:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  15178:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  15179:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15180:        fprintf(ficrest,"\n");
                   15181:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  15182:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15183:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  15184:        for(age=bage; age <=fage ;age++){
1.235     brouard  15185:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  15186:          if (vpopbased==1) {
                   15187:            if(mobilav ==0){
                   15188:              for(i=1; i<=nlstate;i++)
                   15189:                prlim[i][i]=probs[(int)age][i][k];
                   15190:            }else{ /* mobilav */ 
                   15191:              for(i=1; i<=nlstate;i++)
                   15192:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15193:            }
                   15194:          }
1.219     brouard  15195:          
1.227     brouard  15196:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15197:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15198:          /* printf(" age %4.0f ",age); */
                   15199:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15200:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15201:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15202:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15203:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15204:            }
                   15205:            epj[nlstate+1] +=epj[j];
                   15206:          }
                   15207:          /* printf(" age %4.0f \n",age); */
1.219     brouard  15208:          
1.227     brouard  15209:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15210:            for(j=1;j <=nlstate;j++)
                   15211:              vepp += vareij[i][j][(int)age];
                   15212:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15213:          for(j=1;j <=nlstate;j++){
                   15214:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15215:          }
                   15216:          fprintf(ficrest,"\n");
                   15217:        }
1.208     brouard  15218:       } /* End vpopbased */
1.269     brouard  15219:       free_vector(epj,1,nlstate+1);
1.208     brouard  15220:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15221:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  15222:       printf("done selection\n");fflush(stdout);
                   15223:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  15224:       
1.335     brouard  15225:     } /* End k selection or end covariate selection for nres */
1.227     brouard  15226: 
                   15227:     printf("done State-specific expectancies\n");fflush(stdout);
                   15228:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15229: 
1.335     brouard  15230:     /* variance-covariance of forward period prevalence */
1.269     brouard  15231:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  15232: 
1.227     brouard  15233:     
1.290     brouard  15234:     free_vector(weight,firstobs,lastobs);
1.351     brouard  15235:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  15236:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  15237:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15238:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15239:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15240:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  15241:     free_ivector(tab,1,NCOVMAX);
                   15242:     fclose(ficresstdeij);
                   15243:     fclose(ficrescveij);
                   15244:     fclose(ficresvij);
                   15245:     fclose(ficrest);
                   15246:     fclose(ficpar);
                   15247:     
                   15248:     
1.126     brouard  15249:     /*---------- End : free ----------------*/
1.219     brouard  15250:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  15251:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15252:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  15253:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15254:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  15255:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  15256:   /* endfree:*/
                   15257:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15258:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15259:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  15260:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15261:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  15262:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15263:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15264:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  15265:   free_matrix(matcov,1,npar,1,npar);
                   15266:   free_matrix(hess,1,npar,1,npar);
                   15267:   /*free_vector(delti,1,npar);*/
                   15268:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15269:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  15270:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  15271:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15272:   
                   15273:   free_ivector(ncodemax,1,NCOVMAX);
                   15274:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15275:   free_ivector(Dummy,-1,NCOVMAX);
                   15276:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  15277:   free_ivector(DummyV,-1,NCOVMAX);
                   15278:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  15279:   free_ivector(Typevar,-1,NCOVMAX);
                   15280:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  15281:   free_ivector(TvarsQ,1,NCOVMAX);
                   15282:   free_ivector(TvarsQind,1,NCOVMAX);
                   15283:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  15284:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  15285:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  15286:   free_ivector(TvarFD,1,NCOVMAX);
                   15287:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  15288:   free_ivector(TvarF,1,NCOVMAX);
                   15289:   free_ivector(TvarFind,1,NCOVMAX);
                   15290:   free_ivector(TvarV,1,NCOVMAX);
                   15291:   free_ivector(TvarVind,1,NCOVMAX);
                   15292:   free_ivector(TvarA,1,NCOVMAX);
                   15293:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  15294:   free_ivector(TvarFQ,1,NCOVMAX);
                   15295:   free_ivector(TvarFQind,1,NCOVMAX);
                   15296:   free_ivector(TvarVD,1,NCOVMAX);
                   15297:   free_ivector(TvarVDind,1,NCOVMAX);
                   15298:   free_ivector(TvarVQ,1,NCOVMAX);
                   15299:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  15300:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15301:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15302:   free_ivector(TvarVVA,1,NCOVMAX);
                   15303:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  15304:   free_ivector(TvarVV,1,NCOVMAX);
                   15305:   free_ivector(TvarVVind,1,NCOVMAX);
                   15306:   
1.230     brouard  15307:   free_ivector(Tvarsel,1,NCOVMAX);
                   15308:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  15309:   free_ivector(Tposprod,1,NCOVMAX);
                   15310:   free_ivector(Tprod,1,NCOVMAX);
                   15311:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  15312:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  15313:   free_ivector(Tage,1,NCOVMAX);
                   15314:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  15315:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15316:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  15317: 
                   15318:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15319: 
1.227     brouard  15320:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15321:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  15322:   fflush(fichtm);
                   15323:   fflush(ficgp);
                   15324:   
1.227     brouard  15325:   
1.126     brouard  15326:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  15327:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15328:     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  15329:   }else{
                   15330:     printf("End of Imach\n");
                   15331:     fprintf(ficlog,"End of Imach\n");
                   15332:   }
                   15333:   printf("See log file on %s\n",filelog);
                   15334:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  15335:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15336:   rend_time = time(NULL);  
                   15337:   end_time = *localtime(&rend_time);
                   15338:   /* tml = *localtime(&end_time.tm_sec); */
                   15339:   strcpy(strtend,asctime(&end_time));
1.126     brouard  15340:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15341:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  15342:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  15343:   
1.157     brouard  15344:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15345:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15346:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  15347:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15348: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15349:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15350:   fclose(fichtm);
                   15351:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15352:   fclose(fichtmcov);
                   15353:   fclose(ficgp);
                   15354:   fclose(ficlog);
                   15355:   /*------ End -----------*/
1.227     brouard  15356:   
1.281     brouard  15357: 
                   15358: /* Executes gnuplot */
1.227     brouard  15359:   
                   15360:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  15361: #ifdef WIN32
1.227     brouard  15362:   if (_chdir(pathcd) != 0)
                   15363:     printf("Can't move to directory %s!\n",path);
                   15364:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  15365: #else
1.227     brouard  15366:     if(chdir(pathcd) != 0)
                   15367:       printf("Can't move to directory %s!\n", path);
                   15368:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  15369: #endif 
1.126     brouard  15370:     printf("Current directory %s!\n",pathcd);
                   15371:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15372:   sprintf(plotcmd,"gnuplot");
1.157     brouard  15373: #ifdef _WIN32
1.126     brouard  15374:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15375: #endif
                   15376:   if(!stat(plotcmd,&info)){
1.158     brouard  15377:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15378:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  15379:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  15380:     }else
                   15381:       strcpy(pplotcmd,plotcmd);
1.157     brouard  15382: #ifdef __unix
1.126     brouard  15383:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15384:     if(!stat(plotcmd,&info)){
1.158     brouard  15385:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  15386:     }else
                   15387:       strcpy(pplotcmd,plotcmd);
                   15388: #endif
                   15389:   }else
                   15390:     strcpy(pplotcmd,plotcmd);
                   15391:   
                   15392:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  15393:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  15394:   strcpy(pplotcmd,plotcmd);
1.227     brouard  15395:   
1.126     brouard  15396:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  15397:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  15398:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  15399:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  15400:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  15401:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  15402:       strcpy(plotcmd,pplotcmd);
                   15403:     }
1.126     brouard  15404:   }
1.158     brouard  15405:   printf(" Successful, please wait...");
1.126     brouard  15406:   while (z[0] != 'q') {
                   15407:     /* chdir(path); */
1.154     brouard  15408:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  15409:     scanf("%s",z);
                   15410: /*     if (z[0] == 'c') system("./imach"); */
                   15411:     if (z[0] == 'e') {
1.158     brouard  15412: #ifdef __APPLE__
1.152     brouard  15413:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  15414: #elif __linux
                   15415:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  15416: #else
1.152     brouard  15417:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  15418: #endif
                   15419:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15420:       system(pplotcmd);
1.126     brouard  15421:     }
                   15422:     else if (z[0] == 'g') system(plotcmd);
                   15423:     else if (z[0] == 'q') exit(0);
                   15424:   }
1.227     brouard  15425: end:
1.126     brouard  15426:   while (z[0] != 'q') {
1.195     brouard  15427:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  15428:     scanf("%s",z);
                   15429:   }
1.283     brouard  15430:   printf("End\n");
1.282     brouard  15431:   exit(0);
1.126     brouard  15432: }

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